branch feature/7017 updated (7354d7a -> a469bb2)
This is an automated email from the git hooks/post-receive script. New change to branch feature/7017 in repository observe. See http://git.codelutin.com/observe.git from 7354d7a reorganisation des controleurs des ecrans de type tableaux + correction des sauvegardes des echantillons seine new 52294bf - suppression de tout code utilisant des transaction du module swing (refs #7017) new a469bb2 suppression de tout le code utilisant des transactions sur module swing (refs #7017) The 2 revisions listed above as "new" are entirely new to this repository and will be described in separate emails. The revisions listed as "adds" were already present in the repository and have only been added to this reference. Detailed log of new commits: commit a469bb2e694c41e8cc02d623c277948cb797dfcf Author: Tony CHEMIT <chemit@codelutin.com> Date: Sun May 3 17:22:18 2015 +0200 suppression de tout le code utilisant des transactions sur module swing (refs #7017) commit 52294bf63f828a5df4ed01ea88d3c4d6ed2df7a6 Author: Tony CHEMIT <chemit@codelutin.com> Date: Sun May 3 17:21:07 2015 +0200 - suppression de tout code utilisant des transaction du module swing (refs #7017) Summary of changes: .../src/main/java/fr/ird/observe/DataService.java | 2483 -------------------- .../fr/ird/observe/ObserveApplicationContext.java | 46 +- .../java/fr/ird/observe/ObserveServiceHelper.java | 82 +- .../main/java/fr/ird/observe/db/DataSource.java | 12 - .../java/fr/ird/observe/db/ReplicationService.java | 7 +- .../fr/ird/observe/db/impl/AbstractDataSource.java | 76 - .../test/java/fr/ird/observe/db/DBTestHelper.java | 39 +- .../java/fr/ird/observe/db/DataServiceTest.java | 339 --- .../fr/ird/observe/db/ReplicationServiceTest.java | 15 +- .../its/migration/H2DataSourceMigrationIT.java | 6 +- .../ird/observe/its/report/AbstractReportIT.java | 2 +- .../fr/ird/observe/entities/OpenableEntities.java | 117 +- .../referentiel/LengthWeightParameterDAOImpl.java | 36 + .../referentiel/LengthWeightParemeterHelper.java | 4 +- .../entities/referentiel/ReferenceEntities.java | 4 +- .../observe/entities/referentiel/SexDAOImpl.java | 11 + .../observe/services/AbstractObserveService.java | 50 +- .../ird/observe/services/ReplicationService.java | 32 + .../observe/services/ReplicationServiceImpl.java | 259 +- .../fr/ird/observe/services/data/TripService.java | 3 + .../ird/observe/services/data/TripServiceImpl.java | 27 +- .../data/seine/ActivitySeineServiceImpl.java | 2 +- .../services/operation/ComputeDataService.java | 18 + .../services/operation/ComputeDataServiceImpl.java | 479 ++-- .../services/operation/GpsImportService.java | 27 + .../services/operation/GpsImportServiceImpl.java | 133 ++ .../operation/ObsoleteReferenceToReplace.java | 111 + .../services/operation/SynchronizeService.java | 38 + .../services/operation/SynchronizeServiceImpl.java | 239 ++ .../services/operation/ValidationService.java | 18 + .../services/operation/ValidationServiceImpl.java | 94 + .../services/referential/ReferentialService.java | 22 + .../referential/ReferentialServiceImpl.java | 331 ++- .../main/java/fr/ird/observe/ObserveContext.java | 4 +- .../main/java/fr/ird/observe/ObserveRunner.java | 17 +- .../fr/ird/observe/ui/ObserveMainUIHandler.java | 7 +- .../fr/ird/observe/ui/admin/AdminTabUIHandler.java | 112 +- .../java/fr/ird/observe/ui/admin/AdminUIModel.java | 31 +- .../ui/admin/consolidate/ConsolidateModel.java | 55 +- .../ui/admin/consolidate/ConsolidateUIHandler.java | 129 +- .../ird/observe/ui/admin/export/ExportModel.java | 19 + .../observe/ui/admin/export/ExportUIHandler.java | 44 +- .../observe/ui/admin/gps/ImportGPSUIHandler.java | 131 +- .../observe/ui/admin/save/SaveLocalUIHandler.java | 208 +- .../ui/admin/synchronize/SynchronizeModel.java | 75 +- .../ui/admin/synchronize/SynchronizeUIHandler.java | 352 +-- .../ui/admin/validate/ValidateUIHandler.java | 173 +- .../java/fr/ird/observe/ui/content/ContentUI.jaxx | 4 - .../ird/observe/ui/content/ContentUIHandler.java | 12 - .../observe/ui/content/ContentUIInitializer.java | 11 +- .../ref/ReferentialContentUIInitializer.java | 8 +- .../ird/observe/ui/storage/RemoteUILauncher.java | 8 +- .../ui/storage/StorageBackupUILauncher.java | 7 +- .../ird/observe/ui/storage/StorageUIHandler.java | 46 +- .../ui/tree/loadors/AbstractNodeChildLoador.java | 12 +- 55 files changed, 2086 insertions(+), 4541 deletions(-) delete mode 100644 observe-business/src/main/java/fr/ird/observe/DataService.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/db/DataServiceTest.java create mode 100644 observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParameterDAOImpl.java create mode 100644 observe-entities/src/main/java/fr/ird/observe/entities/referentiel/SexDAOImpl.java create mode 100644 observe-services/src/main/java/fr/ird/observe/services/ReplicationService.java copy observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java => observe-services/src/main/java/fr/ird/observe/services/ReplicationServiceImpl.java (56%) create mode 100644 observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataService.java rename observe-business/src/main/java/fr/ird/observe/ConsolidateDataService.java => observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataServiceImpl.java (80%) create mode 100644 observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportService.java create mode 100644 observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportServiceImpl.java create mode 100644 observe-services/src/main/java/fr/ird/observe/services/operation/ObsoleteReferenceToReplace.java create mode 100644 observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeService.java create mode 100644 observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeServiceImpl.java create mode 100644 observe-services/src/main/java/fr/ird/observe/services/operation/ValidationService.java create mode 100644 observe-services/src/main/java/fr/ird/observe/services/operation/ValidationServiceImpl.java -- To stop receiving notification emails like this one, please contact codelutin.com SCM administrator <admin+scm@list.forge.codelutin.com>.
This is an automated email from the git hooks/post-receive script. New commit to branch feature/7017 in repository observe. See http://git.codelutin.com/observe.git commit 52294bf63f828a5df4ed01ea88d3c4d6ed2df7a6 Author: Tony CHEMIT <chemit@codelutin.com> Date: Sun May 3 17:21:07 2015 +0200 - suppression de tout code utilisant des transaction du module swing (refs #7017) --- .../src/main/java/fr/ird/observe/DataService.java | 2483 -------------------- .../java/fr/ird/observe/db/DataServiceTest.java | 339 --- .../referentiel/LengthWeightParameterDAOImpl.java | 4 + .../observe/entities/referentiel/SexDAOImpl.java | 7 + .../ird/observe/services/ReplicationService.java | 11 + .../observe/services/ReplicationServiceImpl.java | 11 + .../services/operation/ComputeDataService.java | 18 + .../services/operation/ComputeDataServiceImpl.java | 479 ++-- .../services/operation/GpsImportService.java | 11 + .../services/operation/GpsImportServiceImpl.java | 11 + .../operation/ObsoleteReferenceToReplace.java | 111 + .../services/operation/SynchronizeService.java | 11 + .../services/operation/SynchronizeServiceImpl.java | 11 + .../services/operation/ValidationService.java | 18 + .../services/operation/ValidationServiceImpl.java | 94 + 15 files changed, 540 insertions(+), 3079 deletions(-) diff --git a/observe-business/src/main/java/fr/ird/observe/DataService.java b/observe-business/src/main/java/fr/ird/observe/DataService.java deleted file mode 100644 index aee4dc3..0000000 --- a/observe-business/src/main/java/fr/ird/observe/DataService.java +++ /dev/null @@ -1,2483 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.db.constants.DataSourceState; -import fr.ird.observe.db.util.TopiaExecutor; -import fr.ird.observe.db.util.TopiaExecutor2; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.referentiel.LengthWeightParameter; -import fr.ird.observe.entities.referentiel.LengthWeightParemeterHelper; -import fr.ird.observe.entities.referentiel.Ocean; -import fr.ird.observe.entities.referentiel.ReferenceEntities; -import fr.ird.observe.entities.referentiel.Sex; -import fr.ird.observe.entities.referentiel.Species; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.event.TopiaTransactionEvent; -import org.nuiton.topia.event.TopiaTransactionListener; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.DiffState; -import org.nuiton.topia.persistence.util.EntityOperator; -import org.nuiton.topia.persistence.util.Loador; -import org.nuiton.topia.persistence.util.TopiaEntityBinder; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeListenerProxy; -import java.beans.PropertyChangeSupport; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le contrat du service de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataService { - - /** Logger */ - private static final Log log = LogFactory.getLog(DataService.class); - - String PARENT_BEAN = "parentBean"; - - String BEAN = "bean"; - - protected DecoratorService decoratorService; - - protected DataContext dataContext; - - protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); - -// private boolean skipTransactionListener; - - private TopiaTransactionListener transactionListener = new TopiaTransactionListener() { - - public void commit(TopiaTransactionEvent event) { - -// if (skipTransactionListener) { -// return; -// } - - java.util.Set<TopiaEntity> entities = event.getEntities(); - - // pour recenser les referentiels modifies - EnumSet<ObserveEntityEnum> referentiel = - EnumSet.noneOf(ObserveEntityEnum.class); - - // pour referencer les types openables modifies -// boolean touchOpenContext = false; - - // pour referencer les donnees observers modifiees - java.util.Set<TopiaEntity> data = new HashSet<TopiaEntity>(); - - for (TopiaEntity entity : entities) { - if (log.isDebugEnabled()) { - if (event.isLoad(entity)) { - - if (log.isDebugEnabled()) { - log.debug("loaded entity [" + entity.getTopiaId() + "]"); - } - } else if (event.isCreate(entity)) { - if (log.isInfoEnabled()) { - log.info("created entitiy [" + entity.getTopiaId() + "]"); - } - - } else if (event.isUpdate(entity)) { - if (log.isDebugEnabled()) { - log.debug("updated entitiy [" + entity.getTopiaId() + "]"); - } - - } else if (event.isDelete(entity)) { - if (log.isDebugEnabled()) { - log.debug("deleted entitiy [" + entity.getTopiaId() + "]"); - } - } - } - - if (!event.isModification(entity)) { - - // pas de modification, on ne fait rien - continue; - } - - // l'entite a ete modifiee, cree ou supprimee - ObserveEntityEnum constant = - ObserveEntityEnum.valueOf(entity); - - if (constant == null) { - - // non gere (peut-etre une entite technique) - continue; - } - - if (Entities.isReferentielClass(constant)) { - - // c'est un objet du référentiel - referentiel.add(constant); - continue; - } - - // il s'agit d'une donnée utilisateur - data.add(entity); - -// if (OpenableEntities.isOpenable(entity)) { -// touchOpenContext = true; -// } - } - - DataSource source = ObserveServiceHelper.get().getDataSource(); - if (source == null) { - throw new IllegalStateException("No source service registred."); - } - source.checkState(DataSourceState.OPEN); - - if (!referentiel.isEmpty()) { - - // notification de modification de reférentiels - fireReferentielChanged( - source, - referentiel.toArray( - new ObserveEntityEnum[referentiel.size()]) - ); - } - - if (!data.isEmpty()) { - - // notification de modification de reférentiels - fireDataChanged(source, - data.toArray(new TopiaEntity[data.size()]) - ); - } - -// if (touchOpenContext) { -// fireOpenChanged(source); -// } - } - - public void rollback(TopiaTransactionEvent event) { - } - }; - -// protected PropertyChangeListener openListener = new PropertyChangeListener() { -// -// public void propertyChange(PropertyChangeEvent evt) { -// DataService source = (DataService) evt.getSource(); -// DataContext dataContext = source.getDataContext(); -// String[] value = (String[]) evt.getNewValue(); -// if (log.isDebugEnabled()) { -// log.debug("open context changed in data service, will propagate it to " + dataContext); -// log.debug("new open ids : " + Arrays.toString(value)); -// } -// dataContext.populateOpens(value); -// } -// }; - - - public void registerDataSource(DataSource source) { - - ObserveServiceHelper.get().setDataSource(source); - -// addPropertyChangeListener(DataSource.OPEN_PROPERTY_KEY, openListener); - } - - - public void unregisterDataSource(DataSource source) { - - ObserveServiceHelper.get().setDataSource(null); - -// removePropertyChangeListener(DataSource.OPEN_PROPERTY_KEY, openListener); - - // remove all listeners for the referentiel - //FIXMe tchemit 2010-11-30 Perharps we should remove all listeners ? - removeReferentielPropertyChangeListeners(); - } - - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveServiceHelper.getDecoratorService(); - } - return decoratorService; - } - - - public DataContext getDataContext() { - if (dataContext == null) { - dataContext = ObserveServiceHelper.getDataContext(); - } - return dataContext; - } - - // ------------------------------------------------------------------------ - // -- Méthodes de gestion des transactions - // ------------------------------------------------------------------------ - - - public TopiaContext beginTransaction(DataSource source, - String methodName) throws DataSourceException { - source.checkState(DataSourceState.OPEN); - if (log.isDebugEnabled()) { - log.debug("begin tx " + methodName); - } - TopiaContext tx = source.beginTransaction(methodName); - tx.addTopiaTransactionListener(transactionListener); - if (log.isDebugEnabled()) { - log.debug("after begin tx " + methodName); - } - return tx; - } - - - public void rollbackTransaction(DataSource source, - TopiaContext tx, - String txName) throws DataSourceException { - source.checkState(DataSourceState.OPEN); - source.rollbackTransaction(tx, txName); - } - - - public void commitTransaction(DataSource source, - TopiaContext tx, - String txName) throws DataSourceException { - source.checkState(DataSourceState.OPEN); - if (log.isDebugEnabled()) { - log.debug("commit tx " + txName); - } - source.commitTransaction(tx, txName); - if (log.isDebugEnabled()) { - log.debug("after commit tx " + txName); - } - } - - - public void closeTransaction(DataSource source, - TopiaContext tx, - String txName) throws DataSourceException { - source.checkState(DataSourceState.OPEN); - if (log.isDebugEnabled()) { - log.debug("close tx " + txName); - } - tx.removeTopiaTransactionListener(transactionListener); - source.closeTransaction(tx, txName); - if (log.isDebugEnabled()) { - log.debug("after close tx " + txName); - } - } - - // ------------------------------------------------------------------------ - // -- Méthodes métiers de récupération de données - // ------------------------------------------------------------------------ - - -// public String[] getOpenIds(DataSource source) throws DataSourceException { -// -// String[] result = null; -// TopiaContext tx = beginTransaction(source, "getOpenIds"); -// try { -// -// result = source.getOpenIds(tx); -// } finally { -// closeTransaction(source, tx, "getOpenIds"); -// } -// return result; -// } - - - public <E extends TopiaEntity> List<E> getList(DataSource source, Class<E> klass) throws DataSourceException { - - List<E> list = getList(source, klass, null, null); - return list; - } - -// public <E extends TopiaEntity> List<E> getList(DataSource source, Class<E> klass, Predicate<E> predicate) throws DataSourceException { -// List<E> result = getList(source, klass, predicate, null); -// return result; -// } - - - public <E extends TopiaEntity> List<E> getList(DataSource source, - Class<E> klass, - TopiaEntityBinder<E> loador) throws DataSourceException { - List<E> result = getList(source, klass, null, loador); - return result; - } - - - public <E extends TopiaEntity> List<E> getList(DataSource source, - Class<E> klass, - Predicate<E> predicate, - TopiaEntityBinder<E> loador) throws DataSourceException { - if (Entities.isDataClass(klass)) { - // on verifie que l'on a le droit de lire la donnee - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data, no read credential"); - } - return new ArrayList<E>(); - } - } - - if (Entities.isReferentielClass(klass)) { - // on verifie que l'on a le droit de lire la donnee - if (!source.canReadReferentiel()) { - if (log.isDebugEnabled()) { - log.debug("Can not read referentiel, no read credential"); - } - return new ArrayList<E>(); - } - } - - List<E> result; - try { - - result = getList0(source, klass, predicate, loador); - - //TC-20100208 : on peut modifier la liste (pour supprimer par - // exemple les entites non active), on doit donc toujours travailler - // sur une copie de la liste - return new ArrayList<E>(result); - } catch (Exception e) { - throw new DataSourceException(e, "getList"); - } - } - -// public <E extends TopiaEntity> EntityMap findAllUsages(DataSource source, -// E entity) throws DataSourceException { -// -// String txName = "findAllUsages"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TopiaDAO<E> dao; -// dao = source.getDAO(tx, entity); -// -// // always get a fresh version of object -// entity = dao.findByTopiaId(entity.getTopiaId()); -// EntityMap result; -// result = new EntityMap(dao.findAllUsages(entity)); -// if (decoratorService != null) { -// // on charge les entites -// for (Class<? extends TopiaEntity> aClass : result.keySet()) { -// Decorator<? extends TopiaEntity> decorator = -// decoratorService.getDecoratorByType(aClass); -// for (TopiaEntity e : result.get(aClass)) { -// decorator.toString(e); -// } -// } -// } -// return result; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - - -// public <E extends OpenableEntity & TopiaEntity> E getOpen(DataSource source, -// Class<E> klass) throws DataSourceException { -// -// if (!source.canReadData()) { -// if (log.isInfoEnabled()) { -// log.info("Can not read data!"); -// } -// return null; -// } -// String txName = "getOpen"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// E result = source.getOpen(tx, klass); -// if (result != null && klass.equals(TripSeine.class)) { -// ((TripSeine) result).getProgram(); -// } -// return result; -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<Program> getAllProgramStub(DataSource source) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return Collections.emptyList(); -// } -// -// String txName = "getAllProgramStub"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// ProgramDAO dao = (ProgramDAO) source.getDAO(tx, Program.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// List<Program> result = dao.findAllStub(referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } -// -// public Program getProgramStub(DataSource source, String programId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return null; -// } -// -// String txName = "getProgramStub"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// ProgramDAO dao = (ProgramDAO) source.getDAO(tx, Program.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// Program result = dao.findStubByTopiaId(programId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<TripSeine> getTripSeineStubByProgram(DataSource source, String programId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return Collections.emptyList(); -// } -// -// String txName = "getTripSeineStubByProgram"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// List<TripSeine> result = dao.findAllStubByProgramId(programId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } -// -// public TripSeine getTripSeineStub(DataSource source, String tripId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return null; -// } -// -// String txName = "getTripSeineStub"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// TripSeine result = dao.findStubByTopiaId(tripId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - - -// public List<Route> getRouteStubByTrip(DataSource source, String tripSeineId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return Collections.emptyList(); -// } -// -// String txName = "getRouteStubByTrip"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// RouteDAO dao = (RouteDAO) source.getDAO(tx, Route.class); -// List<Route> result = dao.findAllStubByTripId(tripSeineId); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } -// -// public Route getRouteStub(DataSource source, String routeId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return null; -// } -// -// String txName = "getRouteStub"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// RouteDAO dao = (RouteDAO) source.getDAO(tx, Route.class); -// Route result = dao.findStubByTopiaId(routeId); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<ActivitySeine> getActivitySeineStubByRoute(DataSource source, String routeId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return Collections.emptyList(); -// } -// -// String txName = "getActivitySeineStubByRoute"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// ActivitySeineDAO dao = (ActivitySeineDAO) source.getDAO(tx, ActivitySeine.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// List<ActivitySeine> result = dao.findAllStubByRouteId(routeId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public ActivitySeine getActivitySeineStub(DataSource source, String activityId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return null; -// } -// -// String txName = "getActivitySeineStub"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// ActivitySeineDAO dao = (ActivitySeineDAO) source.getDAO(tx, ActivitySeine.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// ActivitySeine result = dao.findStubByTopiaId(activityId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<FloatingObject> getFloatinObjectStubByActivitySeine(DataSource source, String activitySeineId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return Collections.emptyList(); -// } -// -// String txName = "getFloatinObjectStubByActivitySeine"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// FloatingObjectDAO dao = (FloatingObjectDAO) source.getDAO(tx, FloatingObject.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// List<FloatingObject> result = dao.findAllStubByActivityId(activitySeineId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public FloatingObject getFloatinObjectStub(DataSource source, String floatingObjectId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return null; -// } -// -// String txName = "getFloatinObjectStub"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// FloatingObjectDAO dao = (FloatingObjectDAO) source.getDAO(tx, FloatingObject.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// FloatingObject result = dao.findStubByTopiaId(floatingObjectId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<TripLongline> getTripLonglineStubByProgram(DataSource source, String programId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return Collections.emptyList(); -// } -// -// String txName = "getTripLonglineStubByProgram"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// List<TripLongline> result = dao.findAllStubByProgramId(programId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// -// } - -// public TripLongline getTripLonglineStub(DataSource source, String tripId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return null; -// } -// -// String txName = "getTripLonglineStub"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// TripLongline result = dao.findStubByTopiaId(tripId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// -// } - -// public List<ActivityLongline> getActivityLonglineStubByTrip(DataSource source, String tripId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return Collections.emptyList(); -// } -// -// String txName = "getActivityLonglineStubByTrip"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// ActivityLonglineDAO dao = (ActivityLonglineDAO) source.getDAO(tx, ActivityLongline.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// List<ActivityLongline> result = dao.findAllStubByTripId(tripId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public ActivityLongline getActivityLonglineStub(DataSource source, String activityId) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return null; -// } -// -// String txName = "getActivityLonglineStub"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// ActivityLonglineDAO dao = (ActivityLonglineDAO) source.getDAO(tx, ActivityLongline.class); -// ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); -// ActivityLongline result = dao.findStubByTopiaId(activityId, referentielLocale); -// return result; -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public Ocean getTripOcean(DataSource source, String tripId) throws DataSourceException { -// -// String txName = "getTripOcean"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); -// TripSeine result = dao.findByTopiaId(tripId); -// return result.getOcean(); -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - - /** - * Recherche d'un {@link LengthWeightParameter} à partir des paramètres donnés. - * <p/> - * La recherche peut ne peut être aussi exacte que les paramètres donnés : - * <p/> - * Dans le cas d'une espèce faune, si non trouvé alors on recherche sur son - * speciesGroup d'espèce. - * <p/> - * Si non trouvé pour l'océan donné (et que celui-ci est non null), alors on - * recherche avec un ocean vide. - * <p/> - * Si non trouvé sur le gender (et que le gender n'est pas indéterminé) , alors - * on recherche avec le gender indéterminé (gender=0). - * - * @param tx la transaction en cours d'utilisation - * @param species l'espèce sur lequel on recherche le paramétrage - * @param ocean l'ocean recherché (peut être null) - * @param sex le sexe recherché (on essayera sans sexe (sexe.code=0) si non trouvé) - * @param date le jour recherché - * @return le paramétrage adéquate - * @throws DataSourceException pour toute erreur - * @since 1.5 - */ - public <P extends LengthWeightParameter> P findLengthWeightParameter( - TopiaContext tx, - Species species, - Ocean ocean, - Sex sex, - Date date) throws DataSourceException { - - try { - - List<P> list = LengthWeightParemeterHelper.findBySpecies( - (TopiaContextImplementor) tx, - species - ); - - if (CollectionUtils.isEmpty(list)) { - - // aucun parametrage pour le type donne - return null; - } - - // filtrage par ocean - list = LengthWeightParemeterHelper.filterByOcean(list, ocean); - - if (CollectionUtils.isEmpty(list) && ocean != null) { - - // filtre par ocean null - list = LengthWeightParemeterHelper.filterByOcean(list, null); - } - - if (CollectionUtils.isEmpty(list)) { - - // pas d'ocean adequate - return null; - } - - // filtrage par sexe - list = LengthWeightParemeterHelper.filterBySexe(list, sex); - - if (CollectionUtils.isEmpty(list)) { - - Sex unkwonSex = ObserveDAOHelper.getSexDAO(tx).findByCode("0"); - - if (unkwonSex.equals(sex)) { - - // filtrage par sexe indetermine - list = LengthWeightParemeterHelper.filterBySexe(list, unkwonSex); - } - - - } - - if (CollectionUtils.isEmpty(list)) { - - // pas de sexe adequate - return null; - } - - // filtrage par startDate de validite - list = LengthWeightParemeterHelper.filterByDateDebutValidite(list, - date); - - if (CollectionUtils.isEmpty(list)) { - - // pas de date de debut adequate - return null; - } - - // filtrage par endDate de validite - list = LengthWeightParemeterHelper.filterByDateFinValidite(list, - date); - - if (CollectionUtils.isEmpty(list)) { - - // pas de date de fin adequate - return null; - } - - // au final il ne devrait en rester qu'un - - if (list.size() > 1) { - StringBuilder sb = new StringBuilder("Il existe plusieurs paramétrages possibles pour les données suivantes :"); - sb.append("\nEspece : "); - sb.append(getDecoratorService().decorate(species)); - sb.append("\nOcean : "); - sb.append(getDecoratorService().decorate(ocean)); - sb.append("\nSex : "); - sb.append(getDecoratorService().decorate(sex)); - sb.append("\nDate : ").append(date); - sb.append("\nParamétrages trouvés : "); - for (P p : list) { - sb.append("\n - ").append(getDecoratorService().decorate(p)); - } - throw new DataSourceException(sb.toString(), "findLengthWeightParameter"); - } - - P result = list.get(0); - if (log.isDebugEnabled()) { - StringBuilder sb = new StringBuilder("Paramétrage trouvé pour les données suivantes :"); - sb.append("\nEspece : "); - sb.append(getDecoratorService().decorate(species)); - sb.append("\nOcean : "); - sb.append(getDecoratorService().decorate(ocean)); - sb.append("\nSex : "); - sb.append(getDecoratorService().decorate(sex)); - sb.append("\nDate : ").append(date); - sb.append("\nParamétrage: ").append(getDecoratorService().decorate(result)); - log.debug(sb.toString()); - } - return result; - - } catch (Exception e) { - throw new DataSourceException(e, "findLengthWeightParameter"); - } - } - -// protected Sex getUnknownSex(TopiaContext tx) throws TopiaException { -// return ObserveDAOHelper.getSexDAO(tx).findByCode("0"); -// } - -// public int getOpenablePosition(DataSource source, -// String containerId, -// String childId) throws DataSourceException { -// if (childId.startsWith(TripSeine.class.getName())) { -// return getTripSeinePosition(source, containerId, childId); -// } -// if (childId.startsWith(TripLongline.class.getName())) { -// return getTripLonglinePosition(source, containerId, childId); -// } -// if (childId.startsWith(Route.class.getName())) { -// return getRoutePosition(source, containerId, childId); -// } -// if (childId.startsWith(ActivitySeine.class.getName())) { -// return getActivitySeinePosition(source, containerId, childId); -// } -// if (childId.startsWith(ActivityLongline.class.getName())) { -// return getActivityLonglinePosition(source, containerId, childId); -// } -// throw new IllegalStateException("Can not come here!"); -// } - -// protected int getTripSeinePosition(DataSource source, -// String programId, -// String tripId) throws DataSourceException { -// -// String txName = "getTripSeinePosition [" + tripId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); -// int pos = dao.findPositionByProgramId(programId, tripId); -// return pos; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } -// -// protected int getTripLonglinePosition(DataSource source, -// String programId, -// String tripId) throws DataSourceException { -// -// String txName = "getTripLonglinePosition [" + tripId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); -// int pos = dao.findPositionByProgramId(programId, tripId); -// return pos; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } -// -// protected int getRoutePosition(DataSource source, -// String tripId, -// String routeId) throws DataSourceException { -// -// String txName = "getRoutePosition [" + tripId + "/" + routeId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TripSeine maree = source.getDAO(tx, TripSeine.class).findByTopiaId(tripId); -// Route route = maree.getRouteByTopiaId(routeId); -// List<Route> routes = maree.getRoute(); -// Routes.sort(routes); -// return routes.indexOf(route); -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } -// -// protected int getActivitySeinePosition(DataSource source, -// String routeId, -// String activityId) throws DataSourceException { -// -// String txName = "getActivitySeinePosition [" + routeId + "/" + activityId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// Route route = source.getDAO(tx, Route.class).findByTopiaId(routeId); -// ActivitySeine activitySeine = route.getActivitySeineByTopiaId(activityId); -// List<ActivitySeine> activitySeines = route.getActivitySeine(); -// ActivitySeines.sort(activitySeines); -// return activitySeines.indexOf(activitySeine); -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } -// -// protected int getActivityLonglinePosition(DataSource source, -// String tripId, -// String activityId) throws DataSourceException { -// -// String txName = "getActivityLonglinePosition [" + tripId + "/" + activityId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TripLongline trip = source.getDAO(tx, TripLongline.class).findByTopiaId(tripId); -// ActivityLongline activity = trip.getActivityLonglineByTopiaId(activityId); -// List<ActivityLongline> activities = trip.getActivityLongline(); -// ActivityLonglines.sort(activities); -// return activities.indexOf(activity); -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public String getTargetSampleId(DataSource source, -// String setId, -// boolean discarded) throws DataSourceException { -// -// String txName = "getTargetSampleId [" + setId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); -// SetSeine set = dao.findByTopiaId(setId); -// List<TargetSample> list = set.getTargetSample(); -// if (list == null || list.isEmpty()) { -// return null; -// } -// for (TargetSample targetSample : list) { -// if (discarded) { -// if (targetSample.getDiscarded() != null && -// targetSample.getDiscarded()) { -// return targetSample.getTopiaId(); -// } -// } else if (targetSample.getDiscarded() == null || -// !targetSample.getDiscarded()) { -// return targetSample.getTopiaId(); -// } -// } -// return null; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public String getNonTargetSampleId(DataSource source, -// String setId) throws DataSourceException { -// -// String txName = "getNonTargetSampleId [" + setId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); -// SetSeine set = dao.findByTopiaId(setId); -// List<NonTargetSample> list = set.getNonTargetSample(); -// if (list == null || list.isEmpty()) { -// return null; -// } -// return list.get(0).getTopiaId(); -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<Species> getAvailableEspeceForTargetSample(DataSource source, -// String setId, -// boolean discarded) throws DataSourceException { -// -// String txName = "getAvailableEspeceForTargetSample [" + setId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// List<Species> speciess = new ArrayList<Species>(); -// -// TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); -// SetSeine set = dao.findByTopiaId(setId); -// -// // on recupere la liste des species thon utilisees dans le rejet -// Collection<TargetCatch> discardeds = set.getTargetCatch(); -// -// // on filtre sur les speciess monté sur le pont et rejetée -// -// if (discardeds != null) { -// for (TargetCatch discardedt : discardeds) { -// boolean keep; -// -// if (discarded) { -// -// // on ne conserve que les speciess des discardeds montees sur le pont et discardedes -// keep = discardedt.isDiscarded() && discardedt.getBroughtOnDeck(); -// -// } else { -// -// // on ne conserve que les species des discardeds -// keep = !discardedt.isDiscarded(); -// } -// -// if (keep && -// !speciess.contains(discardedt.getWeightCategory().getSpecies())) { -// speciess.add(discardedt.getWeightCategory().getSpecies()); -// } -// } -// } -// return speciess; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<Species> getAvailableEspeceForNonTargetSample(DataSource source, -// String setId) throws DataSourceException { -// -// String txName = "getAvailableEspeceForNonTargetSample [" + setId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// List<Species> speciess = new ArrayList<Species>(); -// -// TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); -// SetSeine set = dao.findByTopiaId(setId); -// -// // on recupere la liste des species faune utilisees dans le rejet -// Collection<NonTargetCatch> discardeds = set.getNonTargetCatch(); -// -// if (discardeds != null) { -// for (NonTargetCatch discarded : discardeds) { -// // on retient toute les speciess (capturées ou rejetées) -// if (!speciess.contains(discarded.getSpecies())) { -// speciess.add(discarded.getSpecies()); -// } -// } -// } -// -// return speciess; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<Section> getSections(DataSource source, String setLonglineId) throws DataSourceException { -// String txName = "getSections [" + setLonglineId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// TopiaDAO<Section> dao = source.getDAO(tx, Section.class); -// -// List<Section> sections = dao.findAllByProperties(Section.PROPERTY_SET_LONGLINE + "." + Section.TOPIA_ID, setLonglineId); -// -// if (!sections.isEmpty()) { -// -// Decorator<Section> sectionDecorator = getDecoratorService().getDecoratorByType(Section.class); -// Decorator<Basket> basketDecorator = getDecoratorService().getDecoratorByType(Basket.class); -// Decorator<Branchline> branchlineDecorator = getDecoratorService().getDecoratorByType(Branchline.class); -// -// for (Section section : sections) { -// -// sectionDecorator.toString(section); -// -// if (!section.isBasketEmpty()) { -// -// for (Basket basket : section.getBasket()) { -// -// basketDecorator.toString(basket); -// -// if (!basket.isBranchlineEmpty()) { -// -// for (Branchline branchline : basket.getBranchline()) { -// -// branchlineDecorator.toString(branchline); -// -// } -// } -// -// } -// } -// } -// } -// -// return sections; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// -// } - -// public List<Species> loadDecoratedSpecies(DataSource source, String speciesListCode) throws DataSourceException { -// String txName = "loadDecoratedSpecies [" + speciesListCode + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// List<Species> speciess = new ArrayList<Species>(); -// -// SpeciesListDAO dao = (SpeciesListDAO) source.getDAO(tx, SpeciesList.class); -// SpeciesList speciesList = dao.findByTopiaId(speciesListCode); -// -// speciess.addAll(speciesList.getSpecies()); -// -// Decorator<Species> decorator = getDecoratorService().getDecoratorByType(Species.class); -// -// for (Species species : speciess) { -// decorator.toString(species); -// } -// -// return speciess; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - - -// public java.util.Set<String> getSpeciesListSpeciesIds(DataSource source, String speciesListId) throws DataSourceException { -// String txName = "getSpeciesListSpeciesIds [" + speciesListId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// -// SpeciesListDAO dao = (SpeciesListDAO) source.getDAO(tx, SpeciesList.class); -// SpeciesList speciesList = dao.findByTopiaId(speciesListId); -// -// java.util.Set<String> ids = -// Sets.newHashSet( -// TopiaEntityHelper.getTopiaIdList( -// speciesList.getSpecies())); -// -// return ids; -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public boolean canUseNonTargetSample(DataSource source, -// String setId) throws DataSourceException { -// -// String txName = "canUseNonTargetSample [" + setId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); -// SetSeine set = dao.findByTopiaId(setId); -// -// return set.canUseNonTargetSample(); -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public boolean canUseTargetSample(DataSource source, -// String setId, -// boolean discarded) throws DataSourceException { -// -// String txName = "canUseTargetSample [" + setId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); -// SetSeine set = dao.findByTopiaId(setId); -// -// return set.canUseTargetSample(discarded); -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public void getObsoleteEspeceForNonTargetSample(DataSource source, -// String setId, -// List<Species> speciessUsed, -// Collection<Species> speciessToDelete, -// List<NonTargetLength> tailleToDelete) throws DataSourceException { -// -// String txName = "getObsoleteEspeceForNonTargetSample [" + setId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); -// SetSeine set = dao.findByTopiaId(setId); -// -// -// if (set.isNonTargetSampleEmpty()) { -// return; -// } -// -// NonTargetSample echantillon = set.getNonTargetSample().get(0); -// -// if (echantillon.isNonTargetLengthEmpty()) { -// return; -// } -// -// for (NonTargetLength taille : echantillon.getNonTargetLength()) { -// Species tailleEspece = taille.getSpecies(); -// if (!speciessUsed.contains(tailleEspece)) { -// // l'species n'existe plus dans les rejet faune, -// // on doit le supprimer -// tailleToDelete.add(taille); -// speciessToDelete.add(tailleEspece); -// if (log.isDebugEnabled()) { -// log.debug("remove obsolote echantillon " + taille + -// " for species " + tailleEspece); -// } -// } -// } -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// -// } - -// public void getObsoleteEspeceForTargetSample(DataSource source, -// String setId, -// Collection<Species> speciessUsed, -// Collection<Species> speciessToDelete, -// List<TargetLength> tailleToDelete, boolean discarded) throws DataSourceException { -// -// String txName = "getObsoleteEspeceForTargetSample [" + setId + "]"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); -// SetSeine set = dao.findByTopiaId(setId); -// -// if (set.isTargetSampleEmpty()) { -// return; -// } -// -// TargetSample echantillon = set.getTargetSample(discarded); -// -// if (echantillon == null || echantillon.isTargetLengthEmpty()) { -// return; -// } -// -// for (TargetLength taille : echantillon.getTargetLength()) { -// Species tailleEspece = taille.getSpecies(); -// if (!speciessUsed.contains(tailleEspece)) { -// // l'species n'existe plus dans les rejet faune, -// // on doit le supprimer -// tailleToDelete.add(taille); -// speciessToDelete.add(tailleEspece); -// if (log.isDebugEnabled()) { -// log.debug("remove obsolote echantillon " + taille + -// " for species " + tailleEspece); -// } -// } -// } -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<Program> getPossibleProgramsForTrip(DataSource source, String tripId) throws DataSourceException { -// -// final GearType gearType; -// -// String txName = "getPossibleProgramsForTrip : " + tripId; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// Trip trip; -// -// if (tripId.contains(TripSeine.class.getSimpleName())) { -// trip = source.getDAO(tx, TripSeine.class).findByTopiaId(tripId); -// } else { -// trip = source.getDAO(tx, TripLongline.class).findByTopiaId(tripId); -// } -// -// gearType = trip.getProgram().getGearType(); -// -// ProgramDAO dao = (ProgramDAO) source.getDAO(tx, Program.class); -// -// List<Program> programs = dao.findAllByGearType(gearType); -// -// for (Program program : programs) { -// decoratorService.decorate(program); -// } -// -// return programs; -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// -// } - -// public void moveTripToProgram(DataSource source, String tripId, String programId) throws DataSourceException { -// -// String txName = "moveTripToProgram : " + tripId + " :: " + programId; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// Trip trip; -// -// if (tripId.contains(TripSeine.class.getSimpleName())) { -// trip = source.getDAO(tx, TripSeine.class).findByTopiaId(tripId); -// } else { -// trip = source.getDAO(tx, TripLongline.class).findByTopiaId(tripId); -// } -// -// ProgramDAO dao = (ProgramDAO) source.getDAO(tx, Program.class); -// -// Program program = dao.findByTopiaId(programId); -// -// trip.setProgram(program); -// -// tx.commitTransaction(); -// -// if (trip.isOpen()) { -// -// // refresh the dataContext -// dataContext.setOpenProgramId(programId); -// -// } -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// -// } - -// public List<SizeMeasure> getCatchLonglineSizeMeasures(DataSource source, CatchLongline bean, final TopiaEntityBinder<SizeMeasure> binder) throws DataSourceException { -// -// String txName = "getSections : " + bean.getTopiaId(); -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TopiaDAO<CatchLongline> dao = source.getDAO(tx, CatchLongline.class); -// CatchLongline catchLongline = dao.findByTopiaId(bean.getTopiaId()); -// List<SizeMeasure> result = new ArrayList<SizeMeasure>(); -// for (SizeMeasure sizeSource : catchLongline.getSizeMeasure()) { -// SizeMeasure target = new SizeMeasureImpl(); -// binder.load(sizeSource, target, true); -// result.add(target); -// } -// return result; -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } -// -// public List<WeightMeasure> getCatchLonglineWeightMeasures(DataSource source, CatchLongline bean, final TopiaEntityBinder<WeightMeasure> binder) throws DataSourceException { -// -// String txName = "getSections : " + bean.getTopiaId(); -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TopiaDAO<CatchLongline> dao = source.getDAO(tx, CatchLongline.class); -// CatchLongline catchLongline = dao.findByTopiaId(bean.getTopiaId()); -// List<WeightMeasure> result = new ArrayList<WeightMeasure>(); -// for (WeightMeasure weightSource : catchLongline.getWeightMeasure()) { -// WeightMeasure target = new WeightMeasureImpl(); -// binder.load(weightSource, target, true); -// result.add(target); -// } -// return result; -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<GearUseFeaturesMeasurementSeine> getDefaultGearUseFeaturesMeasurementSeine(DataSource source, String gearId) throws DataSourceException { -// -// String txName = "getDefaultGearUseFeaturesMeasurementSeine : " + gearId; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// TopiaDAO<Gear> gearDao = source.getDAO(tx, Gear.class); -// Gear gear = gearDao.findByTopiaId(gearId); -// -// Collection<GearCaracteristic> gearCaracteristic = gear.getGearCaracteristic(); -// List<GearUseFeaturesMeasurementSeine> result = new ArrayList<GearUseFeaturesMeasurementSeine>(); -// for (GearCaracteristic caracteristic : gearCaracteristic) { -// GearUseFeaturesMeasurementSeine target = new GearUseFeaturesMeasurementSeineImpl(); -// target.setGearCaracteristic(caracteristic); -// result.add(target); -// } -// -// return result; -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<GearUseFeaturesMeasurementSeine> getGearUseFeaturesMeasurementSeine(DataSource source, GearUseFeaturesSeine bean, final TopiaEntityBinder<GearUseFeaturesMeasurementSeine> binder) throws DataSourceException { -// -// String txName = "getGearUseFeaturesMeasurementSeine : " + bean.getTopiaId(); -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TopiaDAO<GearUseFeaturesSeine> dao = source.getDAO(tx, GearUseFeaturesSeine.class); -// GearUseFeaturesSeine gearUseFeaturesSeine = dao.findByTopiaId(bean.getTopiaId()); -// List<GearUseFeaturesMeasurementSeine> result = new ArrayList<GearUseFeaturesMeasurementSeine>(); -// for (GearUseFeaturesMeasurementSeine measurementSource : gearUseFeaturesSeine.getGearUseFeaturesMeasurement()) { -// GearUseFeaturesMeasurementSeine target = new GearUseFeaturesMeasurementSeineImpl(); -// measurementSource.getGearCaracteristic().getGearCaracteristicType(); -// binder.load(measurementSource, target, true); -// result.add(target); -// } -// return result; -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<GearUseFeaturesMeasurementLongline> getDefaultGearUseFeaturesMeasurementLongline(DataSource source, String gearId) throws DataSourceException { -// -// String txName = "getDefaultGearUseFeaturesMeasurementLongline : " + gearId; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// TopiaDAO<Gear> gearDao = source.getDAO(tx, Gear.class); -// Gear gear = gearDao.findByTopiaId(gearId); -// -// Collection<GearCaracteristic> gearCaracteristic = gear.getGearCaracteristic(); -// List<GearUseFeaturesMeasurementLongline> result = new ArrayList<GearUseFeaturesMeasurementLongline>(); -// for (GearCaracteristic caracteristic : gearCaracteristic) { -// GearUseFeaturesMeasurementLongline target = new GearUseFeaturesMeasurementLonglineImpl(); -// target.setGearCaracteristic(caracteristic); -// result.add(target); -// } -// -// return result; -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - -// public List<GearUseFeaturesMeasurementLongline> getGearUseFeaturesMeasurementLongline(DataSource source, GearUseFeaturesLongline bean, final TopiaEntityBinder<GearUseFeaturesMeasurementLongline> binder) throws DataSourceException { -// -// String txName = "getGearUseFeaturesMeasurementLongline : " + bean.getTopiaId(); -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TopiaDAO<GearUseFeaturesLongline> dao = source.getDAO(tx, GearUseFeaturesLongline.class); -// GearUseFeaturesLongline gearUseFeaturesLongline = dao.findByTopiaId(bean.getTopiaId()); -// List<GearUseFeaturesMeasurementLongline> result = new ArrayList<GearUseFeaturesMeasurementLongline>(); -// for (GearUseFeaturesMeasurementLongline measurementSource : gearUseFeaturesLongline.getGearUseFeaturesMeasurement()) { -// GearUseFeaturesMeasurementLongline target = new GearUseFeaturesMeasurementLonglineImpl(); -// measurementSource.getGearCaracteristic().getGearCaracteristicType(); -// binder.load(measurementSource, target, true); -// result.add(target); -// } -// return result; -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - - public <E extends TopiaEntity> List<String> getEntityIds(DataSource source, Class<E> refClass) - throws DataSourceException { - - String txName = "getEntityIds : " + refClass; - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<E> dao = source.getDAO(tx, refClass); - List<String> result = dao.findAllIds(); - return result; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - -// public List<TripMapPoint> loadTripMapActivityPoints(DataSource source, String id) throws DataSourceException { -// if (!source.canReadData()) { -// if (log.isDebugEnabled()) { -// log.debug("Can not read data!"); -// } -// return null; -// } -// -// String txName = "loadTrip"; -// TopiaContext tx = beginTransaction(source, txName); -// -// List<TripMapPoint> tripMapPoints; -// -// try { -// if (Entities.isSeineId(id)) { -// TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); -// -// tripMapPoints = dao.extractTripMapActivityPoints(id); -// -// } else if (Entities.isLonglineId(id)) { -// -// TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); -// -// tripMapPoints = dao.extractTripMapActivityPoints(id); -// -// } else { -// throw new ObserveTechnicalException(String.format("id '%s' is not seine id or longe line id", id)); -// } -// -// } catch (TopiaException e) { -// throw new DataSourceException(e, txName); -// } finally{ -// closeTransaction(source, tx, txName); -// } -// return tripMapPoints; -// } - - - // ------------------------------------------------------------------------ - // -- Méthodes de chargement de données - // ------------------------------------------------------------------------ - - -// public TopiaEntity loadEntity(DataSource source, -// String id, -// boolean decorate) throws DataSourceException { -// -// String txName = "loadEntity : " + id; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// TopiaEntity result = tx.findByTopiaId(id); -// //FIXME Find a better way to do this... -// if (result instanceof ActivitySeine) { -// -// // on charge toujours sa calée -// ((ActivitySeine) result).getSetSeine(); -// } -// if (result instanceof ActivityLongline) { -// -// // on charge toujours sa calée -// ((ActivityLongline) result).getSetLongline(); -// } -// if (decorate) { -// Decorator<TopiaEntity> decorator = -// getDecoratorService().getDecorator(result); -// if (decorator == null) { -// if (log.isWarnEnabled()) { -// log.warn("Decorateur non trouvé pour l'objet " + result); -// } -// } else { -// decorator.toString(result); -// } -// } -// return result; -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - - - public <E extends TopiaEntity> void loadEditEntity(DataSource source, - String entityId, - TopiaExecutor<E> updator) throws DataSourceException { - - String txName = "loadEditEntity :: " + entityId; - TopiaContext tx = beginTransaction(source, txName); - try { - E bean = source.findByTopiaId(tx, entityId); - updator.execute(tx, bean); - } catch (Exception e) { - throw new DataSourceException("Can not load edit entity " + entityId, e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - -// public <E extends TopiaEntity> List<E> loadEntityAssociation(DataSource source, -// Class<E> entityClass, -// String property, -// String parentId) throws DataSourceException { -// -// TopiaContext tx = beginTransaction(source, "loadEntitiesWithProperties"); -// try { -// -// Class<TopiaEntity> parentclass = TopiaId.getClassName(parentId); -// -// TopiaDAO<?> parentDao = source.getDAO(tx, parentclass); -// -// // get parent entity -// TopiaEntity parent = parentDao.findByTopiaId(parentId); -// -// // get parent operator -// EntityOperator<TopiaEntity> operator = -// ObserveDAOHelper.getOperator(parentclass); -// -// // get property from parent -// List<E> result = (List<E>) operator.get(property, parent); -// -// DecoratorService decoratorService = getDecoratorService(); -// -// if (decoratorService != null) { -// -// // chargement des rendus -// Decorator<E> decorator = -// decoratorService.getDecoratorByType(entityClass); -// for (E e : result) { -// decorator.toString(e); -// } -// } -// return result; -// } catch (TopiaException e) { -// throw new DataSourceException( -// "Can not obtain topiaentity " + -// parentId, e, "loadEntitiesWithProperties"); -// } finally { -// closeTransaction(source, tx, "loadEntitiesWithProperties"); -// } -// } - - public <E extends TopiaEntity, C extends TopiaEntity> void copyAssociation(Class<E> entityType, - Class<C> childEntityType, - String propertyName, - E source, - E target, - TopiaContext targetTx) throws TopiaException { - - EntityOperator<E> operator = ObserveDAOHelper.getOperator(entityType); - - Collection<C> sourceList = (Collection<C>) operator.get(propertyName, source); - - TopiaDAO<C> dao = ObserveDAOHelper.getDAO(targetTx, childEntityType); - - List<C> targetList = Lists.newArrayListWithCapacity(sourceList.size()); - for (C sourceC : sourceList) { - - C targetC = dao.findByTopiaId(sourceC.getTopiaId()); - targetList.add(targetC); - } - operator.set(propertyName, target, targetList); - - } - -// public String getSensorUsedDataFilename(DataSource source, SensorUsed sensorUSed) throws DataSourceException { -// -// String txName = "getSensorUsedDataFilename"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// TripLongline tripLongline = source.getOpen(tx, TripLongline.class); -// -// StringBuilder filenameBuilder = new StringBuilder("sensorData"); -// String code = tripLongline.getVessel().getCode(); -// filenameBuilder.append("-").append(code); -// -// Date startDate = tripLongline.getStartDate(); -// filenameBuilder.append("-").append(new SimpleDateFormat("yyyy.MM.dd").format(startDate)); -// -// SensorType sensorType = sensorUSed.getSensorType(); -// if (sensorType != null && sensorType.getCode() != null) { -// filenameBuilder.append("-").append(sensorType.getCode()); -// } -// -// String sensorSerialNo = sensorUSed.getSensorSerialNo(); -// if (sensorSerialNo != null) { -// filenameBuilder.append("-").append(sensorSerialNo); -// } -// filenameBuilder.append("-").append(sensorUSed.getDataFilename()); -// -// String filename = filenameBuilder.toString(); -// return filename; -// -// } finally { -// -// closeTransaction(source, tx, txName); -// -// } -// -// } - -// public String getTdrDataFilename(DataSource source, Tdr tdr) throws DataSourceException { -// -// String txName = "getTdrDataFilename"; -// TopiaContext tx = beginTransaction(source, txName); -// -// try { -// -// TripLongline tripLongline = source.getOpen(tx, TripLongline.class); -// -// StringBuilder filenameBuilder = new StringBuilder("tdr"); -// String code = tripLongline.getVessel().getCode(); -// filenameBuilder.append("-").append(code); -// -// Date startDate = tripLongline.getStartDate(); -// filenameBuilder.append("-").append(new SimpleDateFormat("yyyy.MM.dd").format(startDate)); -// -// String homeId = tdr.getHomeId(); -// if (homeId != null) { -// filenameBuilder.append("-").append(homeId); -// } -// -// String serialNo = tdr.getSerialNo(); -// if (serialNo != null) { -// filenameBuilder.append("-").append(serialNo); -// } -// filenameBuilder.append("-").append(tdr.getDataFilename()); -// -// String filename = filenameBuilder.toString(); -// return filename; -// -// } finally { -// -// closeTransaction(source, tx, txName); -// -// } -// -// } - -// public <E extends TopiaEntity> List<E> loadDecoratedEntities(DataSource source, -// Class<E> entityClass) throws DataSourceException { -// -// String txName = "loadEntities :: " + entityClass.getName(); -// TopiaContext tx = beginTransaction(source, txName); -// Decorator<E> decorator = getDecoratorService().getDecoratorByType(entityClass); -// try { -// List<E> result = -// source.loadDecoratedEntities(tx, entityClass, decorator); -// return result; -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - - - public <E extends TopiaEntity> List<E> loadDecoratedEntities(DataSource source, - Class<E> entityClass, - TopiaExecutor<E> loador) throws DataSourceException { - - String txName = "loadDecoratedEntities :: " + entityClass.getName(); - TopiaContext tx = beginTransaction(source, txName); - Decorator<E> decorator = getDecoratorService().getDecoratorByType(entityClass); - try { - List<E> result = - source.loadDecoratedEntities(tx, entityClass, decorator); - - if (CollectionUtils.isNotEmpty(result)) { - for (E e : result) { - try { - loador.execute(tx, e); - } catch (TopiaException e1) { - throw new DataSourceException( - "Can not obtain load entity " + e.getTopiaId(), e1, txName); - } - } - } - return result; - } finally { - closeTransaction(source, tx, txName); - } - } - - // ------------------------------------------------------------------------ - // -- Méthodes de création - mise à jour - suppression de données - // ------------------------------------------------------------------------ - - - public <E extends TopiaEntity, P extends TopiaEntity> E preCreate(DataSource source, - String parentBeanId, - E bean, - Loador<E> binder, - TopiaExecutor2<P, E> creator) throws DataSourceException { - - String txName = "preCreate"; - TopiaContext tx = beginTransaction(source, txName); - try { - P parentBean = null; - - if (parentBeanId != null) { - - // il y a un parent a recuperer - try { - parentBean = source.<P>findByTopiaId(tx, parentBeanId); - } catch (TopiaException e) { - - // pas possible de recuperer le parent - throw new DataSourceException(e, txName); - } - - checkNotNullAndExistingEntity(PARENT_BEAN, parentBean); - } - - // on charge le bean - binder.load(null, bean, true); - - checkNotNullAndNoneExistingEntity(BEAN, bean); - - E result; - if (creator == null) { - result = bean; - } else { - try { - result = creator.execute(tx, parentBean, bean); - } catch (TopiaException ex) { - throw new DataSourceException(ex, txName); - } - } - return result; - } finally { - closeTransaction(source, tx, txName); - } - } - - - public <E extends TopiaEntity, P extends TopiaEntity> E create(DataSource source, - String parentBeanId, - E bean, - Loador<E> binder, - TopiaExecutor2<P, E> creator) throws DataSourceException { - - checkNotNullAndNoneExistingEntity("bean", bean); - - String txName = "create"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - P parentBean = null; - - if (parentBeanId != null) { - - // il y a un parent a recuperer - try { - parentBean = source.<P>findByTopiaId(tx, parentBeanId); - } catch (TopiaException e) { - - // pas possible de recuperer le parent - throw new DataSourceException(e, txName); - } - - checkNotNullAndExistingEntity(PARENT_BEAN, parentBean); - } - - E beanToSave = creator.execute(tx, parentBean, bean); - - if (binder != null) { - binder.load(bean, beanToSave, false); - } - - if (parentBean == null) { - - // sauvegarde de l'entité autolastNamee - TopiaDAO<E> dao = source.getDAO(tx, beanToSave); - dao.update(beanToSave); - } else { - - // sauvegarde du père de l'entité - TopiaDAO<P> dao = source.getDAO(tx, parentBean); - dao.update(parentBean); - } - - commitTransaction(source, tx, txName); - return beanToSave; - } catch (Exception e) { - rollbackTransaction(source, tx, txName); - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public <E extends TopiaEntity, P extends TopiaEntity> E update(DataSource source, - String parentBeanId, - E bean, - TopiaExecutor2<P, E> updator) throws DataSourceException { - - checkNotNullAndExistingEntity("bean", bean); - - String txName = "update"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - P parentBean = null; - - if (parentBeanId != null) { - - // il y a un parent a recuperer - try { - parentBean = source.<P>findByTopiaId(tx, parentBeanId); - } catch (TopiaException e) { - - // pas possible de recuperer le parent - throw new DataSourceException(e, txName); - } - - checkNotNullAndExistingEntity(PARENT_BEAN, parentBean); - } - - E beanToSave; - - try { - beanToSave = source.<E>findByTopiaId(tx, bean.getTopiaId()); - } catch (TopiaException e) { - - // pas possible de recuperer le parent - throw new DataSourceException(e, txName); - } - - checkNotNullAndExistingEntity(BEAN, beanToSave); - - beanToSave = updator.execute(tx, parentBean, beanToSave); - - if (parentBean == null) { - - // sauvegarde de l'entité autolastNamee - TopiaDAO<E> dao = source.getDAO(tx, beanToSave); - dao.update(beanToSave); - } else { - - // sauvegarde du père de l'entité - TopiaDAO<P> dao = source.getDAO(tx, parentBean); - dao.update(parentBean); - } - - commitTransaction(source, tx, txName); - return beanToSave; - } catch (Exception e) { - rollbackTransaction(source, tx, txName); - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - -// public void updateOpenProperty(DataSource source, -// String id, -// boolean newValue) throws DataSourceException { -// -// if (!source.canWriteData()) { -// -// // pas autorisé à écrire des données observer -// return; -// } -// -// String txName = "updateOpenProperty :: " + id + " - " + newValue; -// TopiaContext tx = null; -// try { -// tx = beginTransaction(source, txName); -// OpenableEntity beanToSave = source.findByTopiaId(tx, id); -// beanToSave.setOpen(newValue); -// commitTransaction(source, tx, txName); -// } catch (TopiaException e) { -// throw new DataSourceException( -// "Can not update open state for " + id, e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// } - - - @SuppressWarnings({"unchecked"}) - public <P extends TopiaEntity, E extends TopiaEntity> void delete(DataSource source, - String parentBeanId, - E bean, - TopiaExecutor2<P, E> deletor) throws DataSourceException { - - checkNotNullAndExistingEntity("bean", bean); - - String txName = "delete"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - P parentBean = null; - - TopiaDAO<TopiaEntity> parentDao = null; - - if (parentBeanId != null) { - parentBean = (P) tx.findByTopiaId(parentBeanId); - - checkNotNullAndExistingEntity("parentBean", parentBean); - - parentDao = source.getDAO(tx, (TopiaEntity) parentBean); - } - - E beanToDelete = (E) tx.findByTopiaId(bean.getTopiaId()); - - deletor.execute(tx, parentBean, beanToDelete); - - if (parentBeanId != null) { - - parentDao.update(parentBean); - } - - commitTransaction(source, tx, txName); - } catch (Exception e) { - rollbackTransaction(source, tx, "create"); - if (e instanceof DataSourceException) { - throw (DataSourceException) e; - } - throw new DataSourceException(e, txName); - } - } - - - public void close() { - decoratorService = null; - dataContext = null; - } - - - public <E extends TopiaEntity> void checkNotNullAndNoneExistingEntity(String variableName, E entity) { - TopiaEntityHelper.checkNotNullAndNoneExistingEntity(variableName, entity); - } - - - public <E extends TopiaEntity> void checkNotNullAndExistingEntity(String variableName, E entity) { - TopiaEntityHelper.checkNotNullAndExistingEntity(variableName, entity); - } - - - public DiffState.DiffStateMap buildReferentielDifferentiel(final DataSource srcService, - final DataSource dstService, - final SendMessageAble messanger) - throws DataSourceException { - try { - final DiffState.DiffStateMap result = DiffState.newMap(); - ReferenceEntities.walk(new ReferenceEntities.ReferentielWalker() { - - - public <E extends TopiaEntity> void walk( - Class<E> contractClass) throws Exception { - - String s = t(DecoratorService.getEntityLabel(contractClass)); - String message = - t("observe.service.build.synchro.referentiel", s); - if (messanger != null) { - messanger.sendMessage(message); - } - if (log.isInfoEnabled()) { - log.info(message); - } - List<E> list = getList(srcService, contractClass); - List<E> list2 = getList(dstService, contractClass); - DiffState.DiffStateMap tmp; - // recuperation du differentiel pour le type d'entitétmp = - tmp = TopiaEntityHelper.buildDifferentiel(list, list2); - // ajout au resultat - DiffState.addAll(result, tmp); - // on nettoie - DiffState.clear(tmp); - } - }); - DiffState.removeEmptyStates(result); - return result; - } catch (DataSourceException ex) { - throw ex; - } catch (Exception ex) { - throw new DataSourceException(ex, "buildReferentielDifferentiel"); - } - } - - protected <E extends TopiaEntity> List<E> getList0(DataSource source, - Class<E> klass, - Predicate<E> predicate, - TopiaEntityBinder<E> loador) throws Exception { - - TopiaContext tx = beginTransaction(source, "getList0 : " + klass); - try { - TopiaDAO<E> dao = source.getDAO(tx, klass); - List<E> result = dao.findAll(); - - if (predicate != null) { - - // use a filter - result = Lists.newArrayList(Iterables.filter(result, predicate)); - - } - if (loador != null) { - for (E e : result) { - loador.obtainProperties(e); - } - } - return result; - } finally { - closeTransaction(source, tx, "getList0 : " + klass); - } - } - - // ------------------------------------------------------------------------ - // -- Property change support - // ------------------------------------------------------------------------ - - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - -// public void removePropertyChangeListeners() { -// for (PropertyChangeListener listener : pcs.getPropertyChangeListeners()) { -// removePropertyChangeListener(listener); -// } -// } - - public <E extends TopiaEntity> void addReferentielPropertyChangeListener(Class<E> entitClass, PropertyChangeListener listener) { - ObserveEntityEnum constant = ObserveEntityEnum.valueOf(entitClass); - String propertyName = getReferentielPropertyName(constant); - log.info(propertyName + " :" + listener); - addPropertyChangeListener(propertyName, listener); - } - -// public <E extends TopiaEntity> void addDataPropertyChangeListener(Class<E> entitClass, PropertyChangeListener listener) { -// ObserveEntityEnum constant = ObserveEntityEnum.valueOf(entitClass); -// String propertyName = getDataPropertyName(constant); -// addPropertyChangeListener(propertyName, listener); -// } - - public void removeReferentielPropertyChangeListeners() { - for (ObserveEntityEnum constant : Entities.REFERENCE_ENTITIES) { - String propertyName = getReferentielPropertyName(constant); - PropertyChangeListener[] changeListeners = pcs.getPropertyChangeListeners(propertyName); - if (log.isDebugEnabled()) { - log.debug(propertyName + " :" + changeListeners.length); - } - for (PropertyChangeListener listener : - changeListeners) { - if (log.isDebugEnabled()) { - log.debug(propertyName + " :" + listener); - } - removePropertyChangeListener(propertyName, listener); - } - } - } - - protected String getReferentielPropertyName(ObserveEntityEnum constant) { - return DataSource.REFERENTIEL_PROPERTY_KEY + "#" + constant.name(); - } - - protected String getDataPropertyName(ObserveEntityEnum constant) { - return DataSource.DATA_PROPERTY_KEY + "#" + constant.name(); - } - - protected void firePropertyChangedEvent(PropertyChangeEvent event, - String message, - PropertyChangeListener... listeners) { - for (PropertyChangeListener listener : listeners) { - if (log.isInfoEnabled()) { - log.info(message + ", notifiy listener " + listener); - } - listener.propertyChange(event); - } - } - - protected PropertyChangeListener[] getPropertyChangeListener(String propertyName) { - List<PropertyChangeListener> result = new ArrayList<PropertyChangeListener>(); - for (PropertyChangeListener listener : pcs.getPropertyChangeListeners()) { - if (listener instanceof PropertyChangeListenerProxy) { - PropertyChangeListenerProxy proxy = - (PropertyChangeListenerProxy) listener; - if (!propertyName.equals(proxy.getPropertyName())) { - continue; - } - } - result.add(listener); - } - return result.toArray(new PropertyChangeListener[result.size()]); - } - -// public void fireOpenChanged(DataSource source) { -// -// String propertyName = DataSource.OPEN_PROPERTY_KEY; -// -// if (log.isInfoEnabled()) { -// log.info("Open context changed, will notifiy listeners [" + propertyName + "]..."); -// } -// -// // obtain all opens ids -// try { -// -// String[] ids = getOpenIds(source); -// -// String message = Arrays.toString(ids); -// -// PropertyChangeListener[] listeners = getPropertyChangeListener(propertyName); -// if (listeners.length == 0) { -// // pas de listener, on ne fait rien -// -// -// if (log.isInfoEnabled()) { -// log.info("Open context " + message + ", No listener, skip"); -// } -// return; -// } -// -// PropertyChangeEvent event = new PropertyChangeEvent(this, propertyName, null, ids); -// firePropertyChangedEvent(event, "Open context " + message + " changed", listeners); -// -// } catch (DataSourceException e) { -// if (log.isErrorEnabled()) { -// log.error("Could not fire open changed", e); -// } -// } -// } - - protected void fireReferentielChanged(DataSource source, ObserveEntityEnum... types) { - for (ObserveEntityEnum constant : types) { - try { - String propertyName = getReferentielPropertyName(constant); - if (log.isInfoEnabled()) { - log.info("Referentiel [" + constant + "] changed, will notifiy listeners [" + propertyName + "]..."); - } - - PropertyChangeListener[] listeners = getPropertyChangeListener(propertyName); - if (listeners.length == 0) { - // pas de listener, on ne fait rien - - if (log.isInfoEnabled()) { - log.info("Referentiel [" + constant + "] No listener, skip"); - } - return; - } - - List<? extends TopiaEntity> entities = getList(source, constant.getContract()); - if (log.isInfoEnabled()) { - log.info("Referentiel [" + constant + "] new size " + entities.size()); - } - - PropertyChangeEvent event = new PropertyChangeEvent(this, propertyName, null, entities); - firePropertyChangedEvent(event, "Referentiel [" + constant + "] changed", listeners); - } catch (DataSourceException e) { - if (log.isErrorEnabled()) { - log.error("Could not fire referentiel [" + constant + "] changed"); - } - } - } - } - - protected void fireDataChanged(DataSource source, TopiaEntity... types) { - for (TopiaEntity entity : types) { - - ObserveEntityEnum constant = - ObserveEntityEnum.valueOf(entity); - - // une entite donnee observer a ete modifiee, supprimer ou cree - // on notifie tous les écouteurs des données observer - - String propertyName = getDataPropertyName(constant); - if (log.isInfoEnabled()) { - log.info("Data [" + entity.getTopiaId() + "] changed, will notifiy listeners [" + propertyName + "]..."); - } - - PropertyChangeListener[] listeners = getPropertyChangeListener(propertyName); - if (listeners.length == 0) { - // pas de listener, on ne fait rien - - if (log.isDebugEnabled()) { - log.debug("Data [" + entity.getTopiaId() + "] No listener, skip"); - } - return; - } - - PropertyChangeEvent event = new PropertyChangeEvent(this, propertyName, null, entity); - firePropertyChangedEvent(event, "Data [" + entity + "] changed", listeners); - } - } - -// public void deleteTrip(DataSource source, String tripId) throws DataSourceException { -// -// String txName = "deleteTrip"; -// TopiaContext tx = beginTransaction(source, txName); -// try { -// -// if (Entities.isSeineId(tripId)) { -// -// TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); -// TripSeine result = dao.findByTopiaId(tripId); -// dao.delete(result); -// -// } else { -// -// TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); -// TripLongline result = dao.findByTopiaId(tripId); -// dao.delete(result); -// -// } -// -// skipTransactionListener = true; -// try { -// -// commitTransaction(source, tx, txName); -// -// } finally { -// skipTransactionListener = false; -// } -// -// } catch (Exception e) { -// throw new DataSourceException(e, txName); -// } finally { -// closeTransaction(source, tx, txName); -// } -// -// } -} diff --git a/observe-business/src/test/java/fr/ird/observe/db/DataServiceTest.java b/observe-business/src/test/java/fr/ird/observe/db/DataServiceTest.java deleted file mode 100644 index d720a02..0000000 --- a/observe-business/src/test/java/fr/ird/observe/db/DataServiceTest.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.DataService; -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.util.Scripts; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -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.event.TopiaEntityEvent; -import org.nuiton.topia.event.TopiaEntityListener; -import org.nuiton.topia.persistence.TopiaDAO; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; - -/** - * Tests the {@link DataService}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataServiceTest { - - - /** Logger */ - private static final Log log = - LogFactory.getLog(DataServiceTest.class); - - - @BeforeClass - public static void init() throws Exception { - - TestHelper.initTest(DataServiceTest.class); - - TestHelper.createApplicationContext(); - - TestHelper.setConfig(IObserveConfig.DB_VERSION, - Scripts.V_LAST.toString()); - } - - @Before - public void setUp() { - hits = 0; - } - - @After - public void tearDown() throws Exception { - DataSourceFactory.dispose(); - } - - @Test - public void testSetDataSource2() throws Exception { - - DataService service = new DataService(); - - service.addReferentielPropertyChangeListener(Program.class, new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - increment(); - } - }); - - File dir = TestHelper.newLocalDB("testSetDataSource2"); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigEmpty( - "testSetDataSource2", - dir, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD - ); - - Assert.assertNotNull(config); - - DataSource dataSource = DataSourceFactory.newService(config); - - dataSource.doOpen(); - - Assert.assertTrue(dataSource.isOpen()); - - DBTestHelper.assertSchemaCreated( - dataSource, - true - ); - - service.registerDataSource(dataSource); - -// Assert.assertTrue(service.isEnabled()); - - dataSource.getRootCtxt().addTopiaEntityListener(listener); - - Assert.assertEquals(0, hits); - - Program program; - TopiaContext tx = service.beginTransaction(dataSource, "createProgram"); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - program = dao.create(Program.PROPERTY_CODE, "1", Program.PROPERTY_LABEL1, "label1", Program.PROPERTY_LABEL2, "label2"); - - service.commitTransaction(dataSource, tx, "createProgram"); - } finally { - service.closeTransaction(dataSource, tx, "createProgram"); - } - - // un hit de creation - Assert.assertEquals(1, hits); - - tx = service.beginTransaction(dataSource, "loadProgram"); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - - program = dao.findByTopiaId(program.getTopiaId()); - - } finally { - service.closeTransaction(dataSource, tx, "loadProgram"); - } - - // pas de hit de load - Assert.assertEquals(1, hits); - - - tx = service.beginTransaction(dataSource, "updateProgram"); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - program = dao.findByTopiaId(program.getTopiaId()); - - program.setLabel3("label3"); - dao.update(program); - - service.commitTransaction(dataSource, tx, "updateProgram"); - } finally { - service.closeTransaction(dataSource, tx, "updateProgram"); - } - - // un hit de update - Assert.assertEquals(2, hits); - - tx = service.beginTransaction(dataSource, "deleteProgram"); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - - program = dao.findByTopiaId(program.getTopiaId()); - dao.delete(program); - - service.commitTransaction(dataSource, tx, "deleteProgram"); - } finally { - service.closeTransaction(dataSource, tx, "deleteProgram"); - } - - - // un hit de delete - Assert.assertEquals(3, hits); - - } - - @Test - public void testSetDataSource() throws Exception { - - DataService service = new DataService(); - - File dir = TestHelper.newLocalDB("testSetDataSource"); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigEmpty( - "testCreateH2ConfigEmpty", - dir, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD - ); - - Assert.assertNotNull(config); - - DataSource dataSource = DataSourceFactory.newService(config); - - dataSource.doOpen(); - - Assert.assertTrue(dataSource.isOpen()); - - DBTestHelper.assertSchemaCreated( - dataSource, - true - ); - - service.registerDataSource(dataSource); - -// Assert.assertTrue(service.isEnabled()); - - dataSource.getRootCtxt().addTopiaEntityListener(listener); - - Assert.assertEquals(0, hits); - Program program; - TopiaContext tx = service.beginTransaction(dataSource, "createProgram"); - tx.addTopiaEntityListener(listener); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - program = dao.create(Program.PROPERTY_CODE, "1", Program.PROPERTY_LABEL1, "label1", Program.PROPERTY_LABEL2, "label2"); - - service.commitTransaction(dataSource, tx, "createProgram"); - } finally { - service.closeTransaction(dataSource, tx, "createProgram"); - tx.removeTopiaEntityListener(listener); - } - - // un hit de creation - Assert.assertEquals(1, hits); - - tx = service.beginTransaction(dataSource, "loadProgram"); - tx.addTopiaEntityListener(listener); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - - program = dao.findByTopiaId(program.getTopiaId()); - - } finally { - service.closeTransaction(dataSource, tx, "loadProgram"); - tx.removeTopiaEntityListener(listener); - } - - // un hit de load -// Assert.assertEquals(1, hits); - Assert.assertEquals(2, hits); - - - tx = service.beginTransaction(dataSource, "updateProgram"); - tx.addTopiaEntityListener(listener); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - - program = dao.findByTopiaId(program.getTopiaId()); - - program.setLabel3("label3"); - dao.update(program); - - service.commitTransaction(dataSource, tx, "updateProgram"); - } finally { - service.closeTransaction(dataSource, tx, "updateProgram"); - tx.removeTopiaEntityListener(listener); - } - - // un hit de load + update -// Assert.assertEquals(2, hits); - Assert.assertEquals(4, hits); - - tx = service.beginTransaction(dataSource, "deleteProgram"); - tx.addTopiaEntityListener(listener); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - program = dao.findByTopiaId(program.getTopiaId()); - dao.delete(program); - - service.commitTransaction(dataSource, tx, "deleteProgram"); - } finally { - service.closeTransaction(dataSource, tx, "deleteProgram"); - tx.removeTopiaEntityListener(listener); - } - - // un hit de load + delete -// Assert.assertEquals(3, hits); - Assert.assertEquals(6, hits); - - } - - protected int hits; - - public void increment() { - hits++; - } - - final TopiaEntityListener listener = new TopiaEntityListener() { - - @Override - public void create(TopiaEntityEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getEntity().getTopiaId()); - } - increment(); - } - - @Override - public void load(TopiaEntityEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getEntity().getTopiaId()); - } - increment(); - } - - @Override - public void update(TopiaEntityEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getEntity().getTopiaId()); - } - increment(); - } - - @Override - public void delete(TopiaEntityEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getEntity().getTopiaId()); - } - increment(); - } - }; -} diff --git a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParameterDAOImpl.java b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParameterDAOImpl.java new file mode 100644 index 0000000..d079a72 --- /dev/null +++ b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParameterDAOImpl.java @@ -0,0 +1,4 @@ +package fr.ird.observe.entities.referentiel; + +public class LengthWeightParameterDAOImpl<E extends LengthWeightParameter> extends LengthWeightParameterDAOAbstract<E> { +} diff --git a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/SexDAOImpl.java b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/SexDAOImpl.java new file mode 100644 index 0000000..97f220e --- /dev/null +++ b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/SexDAOImpl.java @@ -0,0 +1,7 @@ +package fr.ird.observe.entities.referentiel; + +import javax.annotation.Generated; + +@Generated(value = "org.nuiton.topia.generator.EntityDAOTransformer", date = "Sat May 02 12:01:39 CEST 2015") +public class SexDAOImpl<E extends Sex> extends SexDAOAbstract<E> { +} //SexDAOImpl<E extends Sex> diff --git a/observe-services/src/main/java/fr/ird/observe/services/ReplicationService.java b/observe-services/src/main/java/fr/ird/observe/services/ReplicationService.java new file mode 100644 index 0000000..865a5c5 --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/ReplicationService.java @@ -0,0 +1,11 @@ +package fr.ird.observe.services; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public interface ReplicationService { + +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/ReplicationServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/ReplicationServiceImpl.java new file mode 100644 index 0000000..dcac5bc --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/ReplicationServiceImpl.java @@ -0,0 +1,11 @@ +package fr.ird.observe.services; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ReplicationServiceImpl implements ReplicationService { + +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataService.java b/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataService.java new file mode 100644 index 0000000..9b58b2e --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataService.java @@ -0,0 +1,18 @@ +package fr.ird.observe.services.operation; + +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.services.ObserveService; + +import java.util.Set; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public interface ComputeDataService extends ObserveService{ + + void consolidateTrips(SendMessageAble messager, Set<String> tripIds); + +} diff --git a/observe-business/src/main/java/fr/ird/observe/ConsolidateDataService.java b/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataServiceImpl.java similarity index 80% rename from observe-business/src/main/java/fr/ird/observe/ConsolidateDataService.java rename to observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataServiceImpl.java index ef0999e..e56a919 100644 --- a/observe-business/src/main/java/fr/ird/observe/ConsolidateDataService.java +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataServiceImpl.java @@ -1,32 +1,14 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; +package fr.ird.observe.services.operation; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; -import fr.ird.observe.db.DataSourceException; +import fr.ird.observe.DecoratorService; +import fr.ird.observe.ObserveDAOHelper; +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.entities.Entities; import fr.ird.observe.entities.LengthWeightComputable; import fr.ird.observe.entities.constants.seine.NonTargetCatchComputedValueSource; import fr.ird.observe.entities.constants.seine.SchoolType; @@ -43,11 +25,12 @@ import fr.ird.observe.entities.seine.SetSeine; import fr.ird.observe.entities.seine.TargetLength; import fr.ird.observe.entities.seine.TargetSample; import fr.ird.observe.entities.seine.TripSeine; +import fr.ird.observe.services.AbstractObserveService; +import fr.ird.observe.services.referential.ReferentialService; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.persistence.TopiaDAO; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.util.TopiaEntityHelper; import org.nuiton.topia.persistence.util.TopiaEntityRef; @@ -58,25 +41,24 @@ import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.SortedMap; import static org.nuiton.i18n.I18n.t; /** - * Le service pour consolider les données observers. - * <p/> - * Il s'agit de pouvoir calculer le type de banc d'une activité et de calculer - * les données déductibles des données observées (sur les discardeds faune et les - * échantillons via les relations taille-weight et autres...). + * FIXME A revoir, utiliser un context pour ne pas avoir d'état dans le service + on ne peut plus utiliser de messager + * On retounera un objet de type result. + * + * Created on 5/3/15. * * @author Tony Chemit - chemit@codelutin.com - * @since 1.8 + * @since 4.0 */ -public class ConsolidateDataService { +public class ComputeDataServiceImpl extends AbstractObserveService implements ComputeDataService { - /** Logger */ - private static final Log log = - LogFactory.getLog(ConsolidateDataService.class); + /** Logger. */ + private static final Log log = LogFactory.getLog(ComputeDataServiceImpl.class); private static final String MESSAGE_FORMAT_3 = "[%1$s] %2$s calculé : %3$s (%4$s:%5$s, %6$s:%7$s)"; @@ -87,7 +69,7 @@ public class ConsolidateDataService { TargetLength.PROPERTY_WEIGHT, TargetLength.PROPERTY_WEIGHT_SOURCE); - protected final BeanMonitor nonTargetSampleMonitor = new BeanMonitor( + protected final BeanMonitor nonTargetLengthMonitor = new BeanMonitor( NonTargetLength.PROPERTY_LENGTH, NonTargetLength.PROPERTY_LENGTH_SOURCE, NonTargetLength.PROPERTY_WEIGHT, @@ -104,40 +86,27 @@ public class ConsolidateDataService { NonTargetCatch.PROPERTY_TOTAL_COUNT_COMPUTED_SOURCE ); - protected final BeanMonitor speciesMonitor = new BeanMonitor( - NonTargetLength.PROPERTY_LENGTH_SOURCE, - NonTargetLength.PROPERTY_WEIGHT, - NonTargetLength.PROPERTY_WEIGHT_SOURCE); - - protected Decorator<TripSeine> mareeDecorator; - - protected Decorator<Species> speciesDecorator; - - protected Decorator<ActivitySeine> activityDecorator; - protected String nonTargetCatcheLabel; protected String speciesLabel; - protected String speciesThonLabel; + protected ReferentialService referentialService; - protected final SendMessageAble LOG_ESSAGER = new SendMessageAble() { - @Override - public void sendMessage(String message) { - if (log.isInfoEnabled()) { - log.info(message); - } + protected ReferentialService getReferentialService() { + if (referentialService == null) { + referentialService = newService(ReferentialService.class); } - }; + return referentialService; + } - public String getNonTargetCatcheLabel() { + protected String getNonTargetCatcheLabel() { if (nonTargetCatcheLabel == null) { nonTargetCatcheLabel = t(DecoratorService.getEntityLabel(NonTargetCatch.class)); } return nonTargetCatcheLabel; } - public String getSpeciesLabel() { + protected String getSpeciesLabel() { if (speciesLabel == null) { speciesLabel = t(DecoratorService.getEntityLabel(Species.class)); } @@ -145,45 +114,77 @@ public class ConsolidateDataService { } - public String decorate(TripSeine maree) { - if (mareeDecorator == null) { - mareeDecorator = getDecoratorService().getDecoratorByType(TripSeine.class); - } - return mareeDecorator.toString(maree); + protected void clear() { + + nonTargetLengthMonitor.setBean(null); + targetLengthMonitor.setBean(null); + nonTargetCatchMonitor.setBean(null); + nonTargetCatcheLabel = null; + speciesLabel = null; + } - public String decorate(Species species) { - if (speciesDecorator == null) { - speciesDecorator = - getDecoratorService().getDecoratorByType(Species.class); + @Override + public void consolidateTrips(SendMessageAble messager, Set<String> tripIds) { + + if (messager==null) { + + messager = new SendMessageAble() { + + @Override + public void sendMessage(String message) { + if (log.isInfoEnabled()) { + log.info(message); + } + } + }; + } - return speciesDecorator.toString(species); - } -// public String decorate(Species species) { -// if (speciesThonDecorator == null) { -// speciesThonDecorator = -// getDecoratorService().getDecoratorByType(Species.class); -// } -// return speciesThonDecorator.toString(species); -// } + TopiaDAO<TripSeine> dao = getDao(TripSeine.class); + + List<TripSeine> toUpdate = new ArrayList<TripSeine>(tripIds.size()); + + for (String tripId : tripIds) { + + if (Entities.isSeineId(tripId)) { + + TripSeine trip = dao.findByTopiaId(tripId); + + boolean needUpdate = consolidateTripSeine(messager, trip); + if (needUpdate) { + + // on met a jour la maree en base + dao.update(trip); + + // on conserve une reference sur la maree mise à jour + toUpdate.add(trip); + + } + + } + + } + + // on commite si quelque chose a ete mise a jour + boolean needCommit = !toUpdate.isEmpty(); + + if (needCommit) { + + messager.sendMessage(t("observe.message.consolidate.save.changes", toUpdate.size())); + getTransaction().commitTransaction(); - public String decorate(ActivitySeine activitySeine) { - if (activityDecorator == null) { - activityDecorator = - getDecoratorService().getDecoratorByType(ActivitySeine.class); } - return activityDecorator.toString(activitySeine); + } - public boolean consolidateTrip(SendMessageAble messager, - TopiaContext tx, - TripSeine maree) throws Exception { - String mareeStr = decorate(maree); + protected boolean consolidateTripSeine(SendMessageAble messager, TripSeine maree) { + + clear(); - SendMessageAble messager1 = getMessager(messager); - messager1.sendMessage( - t("observe.message.consolidate.start.maree", mareeStr)); + String mareeStr = decorateEntity(maree); + + messager.sendMessage(t("observe.message.consolidate.start.maree", mareeStr)); // recuperation des ids des sets de la maree String[] activityIds = getActivityIds(maree); @@ -191,9 +192,7 @@ public class ConsolidateDataService { if (activityIds.length == 0) { // pas de set dans cette maree, donc rien a sauvegarder - messager1.sendMessage( - t("observe.message.consolidate.no.activity.from.maree", - mareeStr)); + messager.sendMessage(t("observe.message.consolidate.no.activity.from.maree", mareeStr)); return false; } @@ -212,7 +211,6 @@ public class ConsolidateDataService { TopiaEntity[] path = ref.getPath(); Route route = (Route) path[path.length - 2]; boolean needUpdate = consolidateActivity(messager, - tx, maree, route, activitySeine @@ -224,38 +222,24 @@ public class ConsolidateDataService { if (toUpdate.isEmpty()) { // rien n'a ete modifie - messager1.sendMessage(t("observe.message.consolidate.nothing.to.save.for.maree", - mareeStr)); + messager.sendMessage(t("observe.message.consolidate.nothing.to.save.for.maree", mareeStr)); return false; + } // on devra mettre a jour en base la maree - messager1.sendMessage(t("observe.message.consolidate.maree.need.update", - mareeStr)); - return true; - } + messager.sendMessage(t("observe.message.consolidate.maree.need.update", mareeStr)); - public void clear() { + return true; - nonTargetSampleMonitor.setBean(null); - targetLengthMonitor.setBean(null); - nonTargetCatchMonitor.setBean(null); - mareeDecorator = null; - activityDecorator = null; - speciesDecorator = null; - nonTargetCatcheLabel = null; - speciesLabel = null; - speciesThonLabel = null; } protected boolean consolidateActivity(SendMessageAble messager, - TopiaContext tx, TripSeine maree, Route route, - ActivitySeine activity) throws Exception { + ActivitySeine activity) { - getMessager(messager).sendMessage(t("observe.message.consolidate.start.activity", - decorate(activity))); + messager.sendMessage(t("observe.message.consolidate.start.activity", decorateEntity(activity))); boolean needUpdate = false; SetSeine set = activity.getSetSeine(); @@ -279,7 +263,6 @@ public class ConsolidateDataService { targetLengthMonitor.setBean(targetLength); updateLengthWeightAble( - tx, maree, route.getDate(), targetLength.getSpecies(), @@ -305,17 +288,16 @@ public class ConsolidateDataService { for (NonTargetLength nonTargetLength : nonTargetSample.getNonTargetLength()) { - nonTargetSampleMonitor.setBean(nonTargetLength); + nonTargetLengthMonitor.setBean(nonTargetLength); updateLengthWeightAble( - tx, maree, route.getDate(), nonTargetLength.getSpecies(), nonTargetLength.getSex(), nonTargetLength ); - if (nonTargetSampleMonitor.wasModified()) { + if (nonTargetLengthMonitor.wasModified()) { needUpdate = true; } } @@ -353,7 +335,6 @@ public class ConsolidateDataService { } updateNonTargetCatch( - tx, maree, set, route.getDate(), @@ -368,30 +349,18 @@ public class ConsolidateDataService { return needUpdate; } - protected boolean allNonTargetCatchDataFilled(NonTargetCatch nonTargetCatch) { - return Iterables.all( - Sets.newHashSet(nonTargetCatch.getCatchWeight(), - nonTargetCatch.getTotalCount(), - nonTargetCatch.getMeanWeight(), - nonTargetCatch.getMeanLength()), - Predicates.notNull()); - } - - protected void updateNonTargetCatch(TopiaContext tx, - TripSeine maree, + protected void updateNonTargetCatch(TripSeine maree, SetSeine set, Date jour, - NonTargetCatch nonTargetCatch) throws DataSourceException { + NonTargetCatch nonTargetCatch) { final Species species = nonTargetCatch.getSpecies(); // récupération du référentiel - LengthWeightParameter parametrage = - getDataService().findLengthWeightParameter(tx, - species, - maree.getOcean(), - null, // pas de sexe spécifié - jour); + LengthWeightParameter parametrage = getReferentialService().findLengthWeightParameter(species, + maree.getOcean(), + null, // pas de sexe spécifié + jour); // -- Cas n°1 (calcul uniquement à partir des relations taille - poids) updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); @@ -408,6 +377,7 @@ public class ConsolidateDataService { if (!set.isNonTargetSampleEmpty()) { samples = Collections2.filter(set.getNonTargetSample().iterator().next().getNonTargetLength(), new Predicate<NonTargetLength>() { + @Override public boolean apply(NonTargetLength input) { return species.equals(input.getSpecies()); @@ -448,7 +418,7 @@ public class ConsolidateDataService { } protected void updateNonTargetCatchByLengthWeightRelation(NonTargetCatch nonTargetCatch, - LengthWeightParameter parametrage) throws DataSourceException { + LengthWeightParameter parametrage) { // calcul via le paramétrage taille - poids updateLengthWeightAble( @@ -470,109 +440,7 @@ public class ConsolidateDataService { ); } - protected void computeNonTargetCatchTailleMoyenne(NonTargetCatch nonTargetCatch, - Collection<NonTargetLength> samples, - LengthWeightParameter parametrage) throws DataSourceException { - - Float meanLength = null; - NonTargetCatchComputedValueSource computedSource = null; - - if (CollectionUtils.isNotEmpty(samples)) { - - // on calcul la taille moyenne à partir des échantillons - float totalTaille = 0f; - int nbIndividus = 0; - for (NonTargetLength sample : samples) { - - Integer count = sample.getCount(); - Float length = sample.getLength(); - - if (count != null && length != null) { - nbIndividus += count; - totalTaille += length * count; - } - } - - if (nbIndividus != 0) { - - meanLength = totalTaille / nbIndividus; - - computedSource = NonTargetCatchComputedValueSource.FROM_SAMPLE; - } - } - - if (meanLength == null && parametrage != null) { - - // on prend directement la valeur fournie par le référentiel - - meanLength = parametrage.getMeanLength(); - computedSource = NonTargetCatchComputedValueSource.FROM_REFERENTIEL; - } - - if (meanLength != null) { - - // la taille moyenne a pu etre calculee, on la pousse alors - nonTargetCatch.setMeanLength(meanLength); - nonTargetCatch.setMeanLengthComputedSource(computedSource); - - // on peut aussi relancer la calcul du cas n°1 - updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); - } - - } - - private void computeNonTargetCatchNombreEstime(NonTargetCatch nonTargetCatch, - Collection<NonTargetLength> samples, - LengthWeightParameter parametrage) throws DataSourceException { - - - if (CollectionUtils.isNotEmpty(samples)) { - - // on calcul la taille moyenne à partir des échantillons - int nbIndividus = 0; - for (NonTargetLength sample : samples) { - - Integer count = sample.getCount(); - - if (count != null) { - nbIndividus += count; - } - } - - if (nbIndividus != 0) { - - nonTargetCatch.setTotalCount(nbIndividus); - nonTargetCatch.setTotalCountComputedSource(NonTargetCatchComputedValueSource.FROM_SAMPLE); - - if (nonTargetCatch.getMeanWeight() != null || nonTargetCatch.getMeanLength() != null) { - - // on peut aussi relancer la calcul du cas n°1 - updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); - } - } - } - } - - private void computeNonTargetCatchMeanValues(NonTargetCatch nonTargetCatch, - LengthWeightParameter parametrage) throws DataSourceException { - - if (parametrage != null) { - - nonTargetCatch.setMeanLength(parametrage.getMeanLength()); - nonTargetCatch.setMeanLengthComputedSource(NonTargetCatchComputedValueSource.FROM_REFERENTIEL); - - nonTargetCatch.setMeanWeight(parametrage.getMeanWeight()); - nonTargetCatch.setMeanWeightComputedSource(NonTargetCatchComputedValueSource.FROM_REFERENTIEL); - - if (nonTargetCatch.getMeanWeight() != null || nonTargetCatch.getMeanLength() != null) { - - // on peut aussi relancer la calcul du cas n°1 - updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); - } - } - } - - protected void updateNonTargetCatchPoidsEstimeNbEstimePoidsMoyen(NonTargetCatch nonTargetCatch) throws DataSourceException { + protected void updateNonTargetCatchPoidsEstimeNbEstimePoidsMoyen(NonTargetCatch nonTargetCatch) { Float meanWeight = nonTargetCatch.getMeanWeight(); Float catchWeight = nonTargetCatch.getCatchWeight(); @@ -641,12 +509,11 @@ public class ConsolidateDataService { } } - protected void updateLengthWeightAble(TopiaContext tx, - TripSeine maree, + protected void updateLengthWeightAble(TripSeine maree, Date jour, Species species, Sex sex, - LengthWeightComputable e) throws DataSourceException { + LengthWeightComputable e) { Ocean ocean = maree.getOcean(); @@ -677,8 +544,7 @@ public class ConsolidateDataService { // recherche du parametrage adequate LengthWeightParameter parametrage = - getDataService().findLengthWeightParameter( - tx, + getReferentialService().findLengthWeightParameter( species, ocean, sex, @@ -691,7 +557,7 @@ public class ConsolidateDataService { String message = t("observe.message.consolidate.no.parametrage.found", t(entityLabel), - decorate(species) + decorateEntity(species) ); if (log.isWarnEnabled()) { log.warn(message); @@ -746,7 +612,7 @@ public class ConsolidateDataService { protected void updateLengthWeightAble(Species species, LengthWeightComputable e, - LengthWeightParameter parametrage) throws DataSourceException { + LengthWeightParameter parametrage) { String entityLabel = getSpeciesLabel(); @@ -779,7 +645,7 @@ public class ConsolidateDataService { String message = t("observe.message.consolidate.no.parametrage.found", t(entityLabel), - decorate(species) + decorateEntity(species) ); if (log.isWarnEnabled()) { log.warn(message); @@ -832,6 +698,109 @@ public class ConsolidateDataService { } } + protected void computeNonTargetCatchTailleMoyenne(NonTargetCatch nonTargetCatch, + Collection<NonTargetLength> samples, + LengthWeightParameter parametrage) { + + Float meanLength = null; + NonTargetCatchComputedValueSource computedSource = null; + + if (CollectionUtils.isNotEmpty(samples)) { + + // on calcul la taille moyenne à partir des échantillons + float totalTaille = 0f; + int nbIndividus = 0; + for (NonTargetLength sample : samples) { + + Integer count = sample.getCount(); + Float length = sample.getLength(); + + if (count != null && length != null) { + nbIndividus += count; + totalTaille += length * count; + } + } + + if (nbIndividus != 0) { + + meanLength = totalTaille / nbIndividus; + + computedSource = NonTargetCatchComputedValueSource.FROM_SAMPLE; + } + } + + if (meanLength == null && parametrage != null) { + + // on prend directement la valeur fournie par le référentiel + + meanLength = parametrage.getMeanLength(); + computedSource = NonTargetCatchComputedValueSource.FROM_REFERENTIEL; + } + + if (meanLength != null) { + + // la taille moyenne a pu etre calculee, on la pousse alors + nonTargetCatch.setMeanLength(meanLength); + nonTargetCatch.setMeanLengthComputedSource(computedSource); + + // on peut aussi relancer la calcul du cas n°1 + updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); + } + + } + + private void computeNonTargetCatchNombreEstime(NonTargetCatch nonTargetCatch, + Collection<NonTargetLength> samples, + LengthWeightParameter parametrage) { + + + if (CollectionUtils.isNotEmpty(samples)) { + + // on calcul la taille moyenne à partir des échantillons + int nbIndividus = 0; + for (NonTargetLength sample : samples) { + + Integer count = sample.getCount(); + + if (count != null) { + nbIndividus += count; + } + } + + if (nbIndividus != 0) { + + nonTargetCatch.setTotalCount(nbIndividus); + nonTargetCatch.setTotalCountComputedSource(NonTargetCatchComputedValueSource.FROM_SAMPLE); + + if (nonTargetCatch.getMeanWeight() != null || nonTargetCatch.getMeanLength() != null) { + + // on peut aussi relancer la calcul du cas n°1 + updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); + } + } + } + } + + private void computeNonTargetCatchMeanValues(NonTargetCatch nonTargetCatch, + LengthWeightParameter parametrage) { + + if (parametrage != null) { + + nonTargetCatch.setMeanLength(parametrage.getMeanLength()); + nonTargetCatch.setMeanLengthComputedSource(NonTargetCatchComputedValueSource.FROM_REFERENTIEL); + + nonTargetCatch.setMeanWeight(parametrage.getMeanWeight()); + nonTargetCatch.setMeanWeightComputedSource(NonTargetCatchComputedValueSource.FROM_REFERENTIEL); + + if (nonTargetCatch.getMeanWeight() != null || nonTargetCatch.getMeanLength() != null) { + + // on peut aussi relancer la calcul du cas n°1 + updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); + } + } + } + + //FIXME Use a simple sql query protected String[] getActivityIds(TripSeine maree) { List<String> tmpIds = new ArrayList<String>(); if (!maree.isRouteEmpty()) { @@ -851,17 +820,13 @@ public class ConsolidateDataService { return result; } - protected DataService getDataService() { - DataService service = ObserveServiceHelper.getDataService(); - return service; - } - - protected DecoratorService getDecoratorService() { - DecoratorService service = ObserveServiceHelper.getDecoratorService(); - return service; + protected boolean allNonTargetCatchDataFilled(NonTargetCatch nonTargetCatch) { + return Iterables.all( + Sets.newHashSet(nonTargetCatch.getCatchWeight(), + nonTargetCatch.getTotalCount(), + nonTargetCatch.getMeanWeight(), + nonTargetCatch.getMeanLength()), + Predicates.notNull()); } - protected SendMessageAble getMessager(SendMessageAble messager) { - return messager == null ? LOG_ESSAGER : messager; - } } diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportService.java b/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportService.java new file mode 100644 index 0000000..57770f9 --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportService.java @@ -0,0 +1,11 @@ +package fr.ird.observe.services.operation; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class GpsImportService { + +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportServiceImpl.java new file mode 100644 index 0000000..5390ca1 --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportServiceImpl.java @@ -0,0 +1,11 @@ +package fr.ird.observe.services.operation; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class GpsImportServiceImpl implements GpsImportService { + +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/ObsoleteReferenceToReplace.java b/observe-services/src/main/java/fr/ird/observe/services/operation/ObsoleteReferenceToReplace.java new file mode 100644 index 0000000..08234a6 --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/ObsoleteReferenceToReplace.java @@ -0,0 +1,111 @@ +package fr.ird.observe.services.operation; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.persistence.util.TopiaEntityRef; + +import java.util.List; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class ObsoleteReferenceToReplace { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ObsoleteReferenceToReplace.class); + + /** l'id de l'entité à remplacer */ + String obsoleteId; + + /** l'id de l'entité de remplacement */ + String safeId; + + /** la liste des références à traiter */ + TopiaEntityRef[] refs; + + public String getSafeId() { + return safeId; + } + + public TopiaEntityRef[] getRefs() { + return refs; + } + + public ObsoleteReferenceToReplace(String obsoleteId, String safeId, List<TopiaEntityRef> refs) { + this.obsoleteId = obsoleteId; + this.refs = refs.toArray(new TopiaEntityRef[refs.size()]); + this.safeId = safeId; + } + + public String getObsoleteId() { + return obsoleteId; + } + +// public void doAction(TopiaContext tx) throws TopiaException { +// +// if (log.isInfoEnabled()) { +// log.info("load obsolete object " + obsoleteId); +// } +// +// if (log.isInfoEnabled()) { +// log.info("load safe object " + safeId); +// } +// +// TopiaEntity safeRef = tx.findByTopiaId(safeId); +// +// // on remplace les references +// for (TopiaEntityRef ref : refs) { +// TopiaEntity invoker = ref.getInvoker(); +// +// if (invoker == null) { +// throw new NullPointerException( +// "can not have a null invoker in " + ref); +// } +// +// if (log.isInfoEnabled()) { +// log.info("load invoker object " + invoker.getTopiaId()); +// } +// +// invoker = tx.findByTopiaId(invoker.getTopiaId()); +// +// // switch entity +// +// String path = ref.getInvokerProperty(); +// +// JXPathContext jxcontext = JXPathContext.newContext(invoker); +// +// TopiaEntity oldValue = (TopiaEntity) jxcontext.getValue(path); +// +// if (log.isDebugEnabled()) { +// log.debug("property to switch " + path + " old : " + +// oldValue); +// } +// +// if (log.isInfoEnabled()) { +// log.info("change path : " + path); +// log.info("old value : " + oldValue.getTopiaId()); +// } +// +// jxcontext.setValue(path, safeRef); +// +// TopiaEntity newValue = (TopiaEntity) jxcontext.getValue(path); +// +// if (log.isInfoEnabled()) { +// log.info("new value : " + newValue.getTopiaId()); +// } +// if (log.isDebugEnabled()) { +// log.debug("property to switch " + path + " new : " + +// safeRef); +// log.debug("property to switch " + path + " new Check : " + +// newValue); +// } +// TopiaDAO<TopiaEntity> dao = getDAO(tx, invoker); +// +// dao.update(invoker); +// } +// } + +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeService.java b/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeService.java new file mode 100644 index 0000000..8051a13 --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeService.java @@ -0,0 +1,11 @@ +package fr.ird.observe.services.operation; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public interface SynchronizeService { + +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeServiceImpl.java new file mode 100644 index 0000000..ecba6db --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeServiceImpl.java @@ -0,0 +1,11 @@ +package fr.ird.observe.services.operation; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SynchronizeServiceImpl implements SynchronizeService { + +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/ValidationService.java b/observe-services/src/main/java/fr/ird/observe/services/operation/ValidationService.java new file mode 100644 index 0000000..76f84b5 --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/ValidationService.java @@ -0,0 +1,18 @@ +package fr.ird.observe.services.operation; + +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.services.ObserveService; +import fr.ird.observe.services.model.DataSelectionModel; +import fr.ird.observe.validation.ValidationMessageDetector; + +/** + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public interface ValidationService extends ObserveService { + + void validate(SendMessageAble messager, ValidationMessageDetector detector, DataSelectionModel dataModel); + +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/ValidationServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/operation/ValidationServiceImpl.java new file mode 100644 index 0000000..6fe70a6 --- /dev/null +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/ValidationServiceImpl.java @@ -0,0 +1,94 @@ +package fr.ird.observe.services.operation; + +import fr.ird.observe.DecoratorService; +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.entities.Trip; +import fr.ird.observe.entities.referentiel.Program; +import fr.ird.observe.services.AbstractObserveService; +import fr.ird.observe.services.data.TripService; +import fr.ird.observe.services.model.DataSelectionModel; +import fr.ird.observe.validation.ValidationMessageDetector; +import org.nuiton.topia.persistence.TopiaDAO; +import org.nuiton.topia.persistence.TopiaEntity; + +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * //FIXME A revoir, on doit utiliser un pattern de Request, Context et Result + * //FIXME Le detector doit être interne + * Created on 5/3/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class ValidationServiceImpl extends AbstractObserveService implements ValidationService { + + @Override + public void validate(SendMessageAble messager, ValidationMessageDetector detector, DataSelectionModel dataModel) { + + if (dataModel.isUseReferentiel()) { + + // validation des referentiels selectionnes + + validateReferentiel(messager, detector, dataModel); + } + + if (dataModel.isUseData()) { + + // validation des donnees observateur selectionnee + + validateData(messager, detector, dataModel); + } + + } + + protected void validateData(SendMessageAble messager, + ValidationMessageDetector detector, + DataSelectionModel dataModel) { + + Set<String> tripIds = dataModel.getSelectedData(); + + TripService tripService = newService(TripService.class); + + for (String tripId : tripIds) { + + Trip trip = tripService.getTrip(tripId); + Program program = trip.getProgram(); + + messager.sendMessage(t("observe.message.validation.start.maree", decorateEntity(trip), decorateEntity(program))); + detector.detectMessages(trip); + + } + + } + + protected void validateReferentiel(SendMessageAble messager, + ValidationMessageDetector detector, + DataSelectionModel dataModel) { + + Set<Class<?>> classes = dataModel.getSelectedReferentiel(); + + for (Class<?> klass : classes) { + + Class<? extends TopiaEntity> refClass = (Class<? extends TopiaEntity>) klass; + TopiaDAO<? extends TopiaEntity> dao = getDao(refClass); + + List<String> ids = dao.findAllIds(); + String entityLabel = t(DecoratorService.getEntityLabel(klass)); + messager.sendMessage(t("observe.message.validation.start.referentiel", entityLabel, ids.size())); + + for (String id : ids) { + TopiaEntity entity = dao.findByTopiaId(id); + detector.detectMessages(entity); + } + + ids.clear(); + + } + + } + +} -- To stop receiving notification emails like this one, please contact codelutin.com SCM administrator <admin+scm@list.forge.codelutin.com>.
This is an automated email from the git hooks/post-receive script. New commit to branch feature/7017 in repository observe. See http://git.codelutin.com/observe.git commit a469bb2e694c41e8cc02d623c277948cb797dfcf Author: Tony CHEMIT <chemit@codelutin.com> Date: Sun May 3 17:22:18 2015 +0200 suppression de tout le code utilisant des transactions sur module swing (refs #7017) --- .../fr/ird/observe/ObserveApplicationContext.java | 46 +-- .../java/fr/ird/observe/ObserveServiceHelper.java | 82 +--- .../main/java/fr/ird/observe/db/DataSource.java | 12 - .../java/fr/ird/observe/db/ReplicationService.java | 7 +- .../fr/ird/observe/db/impl/AbstractDataSource.java | 76 ---- .../test/java/fr/ird/observe/db/DBTestHelper.java | 39 +- .../fr/ird/observe/db/ReplicationServiceTest.java | 15 +- .../its/migration/H2DataSourceMigrationIT.java | 6 +- .../ird/observe/its/report/AbstractReportIT.java | 2 +- .../fr/ird/observe/entities/OpenableEntities.java | 117 +++--- .../referentiel/LengthWeightParameterDAOImpl.java | 32 ++ .../referentiel/LengthWeightParemeterHelper.java | 4 +- .../entities/referentiel/ReferenceEntities.java | 4 +- .../observe/entities/referentiel/SexDAOImpl.java | 12 +- .../observe/services/AbstractObserveService.java | 50 ++- .../ird/observe/services/ReplicationService.java | 25 +- .../observe/services/ReplicationServiceImpl.java | 416 ++++++++++++++++++++- .../fr/ird/observe/services/data/TripService.java | 3 + .../ird/observe/services/data/TripServiceImpl.java | 27 +- .../data/seine/ActivitySeineServiceImpl.java | 2 +- .../services/operation/ComputeDataServiceImpl.java | 2 +- .../services/operation/GpsImportService.java | 20 +- .../services/operation/GpsImportServiceImpl.java | 126 ++++++- .../services/operation/SynchronizeService.java | 31 +- .../services/operation/SynchronizeServiceImpl.java | 232 +++++++++++- .../services/referential/ReferentialService.java | 22 ++ .../referential/ReferentialServiceImpl.java | 331 +++++++++++++++- .../main/java/fr/ird/observe/ObserveContext.java | 4 +- .../main/java/fr/ird/observe/ObserveRunner.java | 17 +- .../fr/ird/observe/ui/ObserveMainUIHandler.java | 7 +- .../fr/ird/observe/ui/admin/AdminTabUIHandler.java | 112 +----- .../java/fr/ird/observe/ui/admin/AdminUIModel.java | 31 +- .../ui/admin/consolidate/ConsolidateModel.java | 55 +-- .../ui/admin/consolidate/ConsolidateUIHandler.java | 129 ++----- .../ird/observe/ui/admin/export/ExportModel.java | 19 + .../observe/ui/admin/export/ExportUIHandler.java | 44 +-- .../observe/ui/admin/gps/ImportGPSUIHandler.java | 131 ++----- .../observe/ui/admin/save/SaveLocalUIHandler.java | 208 +---------- .../ui/admin/synchronize/SynchronizeModel.java | 75 ++-- .../ui/admin/synchronize/SynchronizeUIHandler.java | 352 ++++------------- .../ui/admin/validate/ValidateUIHandler.java | 173 ++++----- .../java/fr/ird/observe/ui/content/ContentUI.jaxx | 4 - .../ird/observe/ui/content/ContentUIHandler.java | 12 - .../observe/ui/content/ContentUIInitializer.java | 11 +- .../ref/ReferentialContentUIInitializer.java | 8 +- .../ird/observe/ui/storage/RemoteUILauncher.java | 8 +- .../ui/storage/StorageBackupUILauncher.java | 7 +- .../ird/observe/ui/storage/StorageUIHandler.java | 46 ++- .../ui/tree/loadors/AbstractNodeChildLoador.java | 12 +- 49 files changed, 1832 insertions(+), 1374 deletions(-) diff --git a/observe-business/src/main/java/fr/ird/observe/ObserveApplicationContext.java b/observe-business/src/main/java/fr/ird/observe/ObserveApplicationContext.java index bd17f13..69426b7 100644 --- a/observe-business/src/main/java/fr/ird/observe/ObserveApplicationContext.java +++ b/observe-business/src/main/java/fr/ird/observe/ObserveApplicationContext.java @@ -66,14 +66,6 @@ public class ObserveApplicationContext extends DefaultApplicationContext { public static final JAXXContextEntryDef<GPSService> GPS_SERVICE_ENTRY_DEF = JAXXUtil.newContextEntryDef(GPSService.class); - /** the jaxx context entry to store the consolidate data service */ - public static final JAXXContextEntryDef<ConsolidateDataService> CONSOLIDATE_DATA_SERVICE_ENTRY_DEF = - JAXXUtil.newContextEntryDef(ConsolidateDataService.class); - - /** the jaxx context entry to store the data service */ - public static final JAXXContextEntryDef<DataService> DATA_SERVICE_ENTRY_DEF = - JAXXUtil.newContextEntryDef(DataService.class); - /** the jaxx context entry to store the data service */ public static final JAXXContextEntryDef<DataContext> DATA_CONTEXT_ENTRY_DEF = JAXXUtil.newContextEntryDef(DataContext.class); @@ -135,15 +127,15 @@ public class ObserveApplicationContext extends DefaultApplicationContext { return decoratorService; } - public final DataService getDataService() { - DataService dataService = - DATA_SERVICE_ENTRY_DEF.getContextValue(this); - if (dataService == null) { - dataService = new DataService(); - DATA_SERVICE_ENTRY_DEF.setContextValue(this, dataService); - } - return dataService; - } +// public final DataService getDataService() { +// DataService dataService = +// DATA_SERVICE_ENTRY_DEF.getContextValue(this); +// if (dataService == null) { +// dataService = new DataService(); +// DATA_SERVICE_ENTRY_DEF.setContextValue(this, dataService); +// } +// return dataService; +// } public final BinderService getBinderService() { BinderService service = @@ -166,16 +158,16 @@ public class ObserveApplicationContext extends DefaultApplicationContext { return service; } - public ConsolidateDataService getConsolidateDataService() { - - ConsolidateDataService service = - CONSOLIDATE_DATA_SERVICE_ENTRY_DEF.getContextValue(this); - if (service == null) { - service = new ConsolidateDataService(); - CONSOLIDATE_DATA_SERVICE_ENTRY_DEF.setContextValue(this, service); - } - return service; - } +// public ConsolidateDataService getConsolidateDataService() { +// +// ConsolidateDataService service = +// CONSOLIDATE_DATA_SERVICE_ENTRY_DEF.getContextValue(this); +// if (service == null) { +// service = new ConsolidateDataService(); +// CONSOLIDATE_DATA_SERVICE_ENTRY_DEF.setContextValue(this, service); +// } +// return service; +// } public final DataContext getDataContext() { DataContext result = DATA_CONTEXT_ENTRY_DEF.getContextValue(this); diff --git a/observe-business/src/main/java/fr/ird/observe/ObserveServiceHelper.java b/observe-business/src/main/java/fr/ird/observe/ObserveServiceHelper.java index a904bc1..54b2303 100644 --- a/observe-business/src/main/java/fr/ird/observe/ObserveServiceHelper.java +++ b/observe-business/src/main/java/fr/ird/observe/ObserveServiceHelper.java @@ -25,13 +25,10 @@ import com.google.common.base.Supplier; import fr.ird.observe.db.DataContext; import fr.ird.observe.db.DataSource; import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.db.ReplicationService; import fr.ird.observe.db.impl.H2DataSource; import fr.ird.observe.db.impl.H2DataSourceConfig; import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.gps.GPSService; import fr.ird.observe.validation.ValidationContext; -import fr.ird.observe.validation.ValidationService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.config.ApplicationConfig; @@ -91,6 +88,7 @@ public class ObserveServiceHelper { ObserveServiceHelper.context = context; AbstractDataSourceMigration.setApplicationConfigSupplier(new Supplier<ApplicationConfig>() { + @Override public ApplicationConfig get() { return ObserveServiceHelper.context.getContextValue(ApplicationConfig.class); @@ -112,24 +110,6 @@ public class ObserveServiceHelper { closed = true; } - /** - * Pour instancier un nouveau service de réplication. - * - * @return le nouveau service de réplication - */ - public static ReplicationService newReplicationService() { - return new ReplicationService(); - } - - /** - * Pour instancier un nouveau service de validation. - * - * @return le nouveau service de validation - */ - public static ValidationService newValidationService() { - return new ValidationService(); - } - public static DataContext getDataContext() { checkInit(); ObserveApplicationContext context = get(); @@ -145,43 +125,6 @@ public class ObserveServiceHelper { } /** - * Pour instancier un nouveau service GPS. - * - * @return le service GPS partagé - */ - public static GPSService getGPSService() { - checkInit(); - ObserveApplicationContext context = get(); - GPSService service = context.getGPSService(); - return service; - } - - /** - * Pour récupérer le service de consolidation des données. - * - * @return le service de consolidation des données partagé - */ - public static ConsolidateDataService getConsolidateDataService() { - checkInit(); - ObserveApplicationContext context = get(); - ConsolidateDataService service = context.getConsolidateDataService(); - return service; - - } - - /** - * Pour obtenir l'unique service haut niveau de manipulation des données. - * - * @return le service haut niveau de manipulation des donées. - */ - public static DataService getDataService() { - checkInit(); - ObserveApplicationContext context = get(); - DataService service = context.getDataService(); - return service; - } - - /** * Pour obtenir l'unique service de décoration. * * @return l'instance partagé du service de décoration @@ -223,28 +166,6 @@ public class ObserveServiceHelper { } /** - * Creates a new local temp storage. - * - * @param dir the directory to use to store database - * @param label label of storage - * @return the new service NOT opened - * @throws IOException if any pb while configuring the service - */ - public static DataSource newEmptyTempStorage(File dir, - String label) throws IOException { - - H2DataSourceConfig conf = DataSourceFactory.newH2ConfigEmpty( - label, - dir, - "sa", - "sa".toCharArray() - ); - - H2DataSource service = DataSourceFactory.newService(conf); - return service; - } - - /** * Construit une source de données sur la base locale de l'application. * <p/> * <b>Note:</b> La base locale doit exister, sinon on soulève une @@ -328,4 +249,5 @@ public class ObserveServiceHelper { public static void setUseJMX(boolean useJMX) { ObserveServiceHelper.useJMX = useJMX; } + } diff --git a/observe-business/src/main/java/fr/ird/observe/db/DataSource.java b/observe-business/src/main/java/fr/ird/observe/db/DataSource.java index a99ea23..959d3c5 100644 --- a/observe-business/src/main/java/fr/ird/observe/db/DataSource.java +++ b/observe-business/src/main/java/fr/ird/observe/db/DataSource.java @@ -24,7 +24,6 @@ package fr.ird.observe.db; import fr.ird.observe.db.constants.DataSourceState; import fr.ird.observe.db.event.DataSourceEvent; import fr.ird.observe.db.event.DataSourceListener; -import fr.ird.observe.entities.OpenableEntity; import org.nuiton.decorator.Decorator; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; @@ -45,12 +44,6 @@ import java.util.Properties; */ public interface DataSource { - String OPEN_PROPERTY_KEY = "open"; - - String REFERENTIEL_PROPERTY_KEY = "referentiel"; - - String DATA_PROPERTY_KEY = "data"; - // ------------------------------------------------------------------------- // Methodes de démarrage et fermeture de la source de données // ------------------------------------------------------------------------- @@ -166,11 +159,6 @@ public interface DataSource { <P extends TopiaEntity> TopiaDAO<P> getDAO(TopiaContext context, P entity) throws TopiaException; - <E extends OpenableEntity & TopiaEntity> E getOpen(TopiaContext tx, - Class<E> klass) throws DataSourceException; - - String[] getOpenIds(TopiaContext tx) throws DataSourceException; - /** * Exporte la base de données dans un script gzip-compresse. * <p/> diff --git a/observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java b/observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java index c531527..0c35d49 100644 --- a/observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java +++ b/observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java @@ -153,15 +153,12 @@ public class ReplicationService { TripSeineDAO srcTripDAO = ObserveDAOHelper.getTripSeineDAO(srcCtxt); List<String> allIds = srcTripDAO.findAllIds(); -// List<TripSeine> srcTripSeines = srcTripDAO.findAll(); - if (CollectionUtils.isEmpty(allIds)) { // aucune donnee a repliquer srcService.fireNewMessage( t("observe.storage.message.replicate.data.no.data")); return; } -// topiaIds = TopiaEntityHelper.getTopiaIdArray(srcTripSeines); topiaIds = allIds.toArray(new String[allIds.size()]); } catch (TopiaException e) { @@ -191,9 +188,7 @@ public class ReplicationService { * @param ids les ids des entités à répliquer * @throws DataSourceException if pb */ - public void replicateData(DataSource srcService, - DataSource dstService, - String... ids) throws DataSourceException { + public void replicateData(DataSource srcService, DataSource dstService, String... ids) throws DataSourceException { if (srcService == null) { throw new NullPointerException("srcService can not be null"); } diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSource.java b/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSource.java index 0ee2567..21243f8 100644 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSource.java +++ b/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSource.java @@ -34,16 +34,7 @@ import fr.ird.observe.db.constants.CommonDataSourceConfigParam; import fr.ird.observe.db.constants.DataSourceState; import fr.ird.observe.db.event.DataSourceEvent; import fr.ird.observe.db.event.DataSourceListener; -import fr.ird.observe.entities.OpenableEntity; -import fr.ird.observe.entities.OpenableEntityDAOImpl; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.SetLongline; -import fr.ird.observe.entities.longline.TripLongline; import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TripSeine; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.SessionFactory; @@ -74,7 +65,6 @@ import java.lang.management.ManagementFactory; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Hashtable; @@ -263,72 +253,6 @@ public abstract class AbstractDataSource implements DataSource { } @Override - public <E extends OpenableEntity & TopiaEntity> E getOpen(TopiaContext tx, Class<E> klass) throws DataSourceException { - if (!canReadData()) { - if (log.isInfoEnabled()) { - log.info("Can not read data!"); - } - return null; - } - try { - - TopiaDAO<E> dao = getDAO(tx, klass); - E result = (E) ((OpenableEntityDAOImpl) dao).findByOpen(true); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, "getOpen"); - } - } - - @Override - public String[] getOpenIds(TopiaContext tx) throws DataSourceException { - - List<String> result = new ArrayList<String>(); - - { - TripSeine trip = getOpen(tx, TripSeine.class); - if (trip != null) { - if (trip.getProgram() != null) { - result.add(trip.getProgram().getTopiaId()); - } - result.add(trip.getTopiaId()); - Route route = getOpen(tx, Route.class); - if (route != null) { - result.add(route.getTopiaId()); - ActivitySeine activity = getOpen(tx, ActivitySeine.class); - if (activity != null) { - result.add(activity.getTopiaId()); - SetSeine set = activity.getSetSeine(); - if (set != null) { - result.add(set.getTopiaId()); - } - } - } - } - } - - { - TripLongline trip = getOpen(tx, TripLongline.class); - if (trip != null) { - if (trip.getProgram() != null) { - result.add(trip.getProgram().getTopiaId()); - } - result.add(trip.getTopiaId()); - ActivityLongline activity = getOpen(tx, ActivityLongline.class); - if (activity != null) { - result.add(activity.getTopiaId()); - SetLongline set = activity.getSetLongline(); - if (set != null) { - result.add(set.getTopiaId()); - } - } - } - } - return result.toArray(new String[result.size()]); - } - - @Override public void addDataSourceListener(DataSourceListener listener) { listenerList.add(DataSourceListener.class, listener); } diff --git a/observe-business/src/test/java/fr/ird/observe/db/DBTestHelper.java b/observe-business/src/test/java/fr/ird/observe/db/DBTestHelper.java index 983b894..a89f5e3 100644 --- a/observe-business/src/test/java/fr/ird/observe/db/DBTestHelper.java +++ b/observe-business/src/test/java/fr/ird/observe/db/DBTestHelper.java @@ -21,8 +21,10 @@ */ package fr.ird.observe.db; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import fr.ird.observe.DataService; import fr.ird.observe.IObserveConfig; import fr.ird.observe.ObserveDAOHelper; import fr.ird.observe.ObserveEntityEnum; @@ -41,8 +43,10 @@ import org.apache.commons.logging.LogFactory; import org.hibernate.jdbc.Work; import org.junit.Assert; import org.junit.Assume; +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.util.version.Version; @@ -80,7 +84,7 @@ public class DBTestHelper { if (Modifier.isAbstract(c.getModifiers())) { continue; } - List<?> r = dataService.getList(service, c); + List<?> r = getList(service, c, null); Assert.assertNotNull(r); if (noData) { Assert.assertEquals(0, r.size()); @@ -88,8 +92,6 @@ public class DBTestHelper { } } - static DataService dataService = new DataService(); - public static void assertReferentiel(DataSource localService, DataSource importService, ObserveEntityEnum... empty) @@ -102,10 +104,9 @@ public class DBTestHelper { List<ObserveEntityEnum> observeEntityEnums = Arrays.asList(empty); // on verifie que le referentiel existe sur la nouvelle base - for (ObserveEntityEnum constant : - Entities.REFERENCE_ENTITIES) { + for (ObserveEntityEnum constant : Entities.REFERENCE_ENTITIES) { Class<? extends TopiaEntity> c = constant.getContract(); - List<?> actual = dataService.getList(localService, c); + List<?> actual = getList(localService, c, null); Assert.assertNotNull(actual); if (!observeEntityEnums.contains(constant)) { // FIXME Remove the empty reference list when all references will be filled @@ -117,7 +118,7 @@ public class DBTestHelper { } // Assert.assertFalse(c.getName(), actual.isEmpty()); if (importService != null) { - List<?> expected = dataService.getList(importService, c); + List<?> expected = getList(importService, c, null); Assert.assertNotNull(expected); Assert.assertEquals(expected.size(), actual.size()); } @@ -129,6 +130,28 @@ public class DBTestHelper { } } + public static <E extends TopiaEntity> List<E> getList(DataSource source, + Class<E> klass, + Predicate<E> predicate) throws DataSourceException { + + TopiaContext tx = source.beginTransaction("getList0 : " + klass); + try { + TopiaDAO<E> dao = source.getDAO(tx, klass); + List<E> result = dao.findAll(); + + if (predicate != null) { + + // use a filter + result = Lists.newArrayList(Iterables.filter(result, predicate)); + + } + + return result; + } finally { + source.closeTransaction(tx, "getList0 : " + klass); + } + } + protected static final Set<ObserveEntityEnum> REFERENCE_TO_FILL = Sets.newHashSet( Arrays.asList(ObserveEntityEnum.FpaZone, ObserveEntityEnum.BaitHaulingStatus, diff --git a/observe-business/src/test/java/fr/ird/observe/db/ReplicationServiceTest.java b/observe-business/src/test/java/fr/ird/observe/db/ReplicationServiceTest.java index f5b8341..61b6ecd 100644 --- a/observe-business/src/test/java/fr/ird/observe/db/ReplicationServiceTest.java +++ b/observe-business/src/test/java/fr/ird/observe/db/ReplicationServiceTest.java @@ -21,8 +21,12 @@ */ package fr.ird.observe.db; -import fr.ird.observe.ObserveServiceHelper; import fr.ird.observe.db.impl.H2DataSource; +import fr.ird.observe.entities.referentiel.Country; +import fr.ird.observe.entities.referentiel.Program; +import fr.ird.observe.entities.referentiel.Species; +import fr.ird.observe.entities.referentiel.Vessel; +import fr.ird.observe.entities.referentiel.seine.WeightCategory; import fr.ird.observe.entities.seine.ActivitySeine; import fr.ird.observe.entities.seine.FloatingObject; import fr.ird.observe.entities.seine.NonTargetCatch; @@ -33,11 +37,6 @@ import fr.ird.observe.entities.seine.TargetCatch; import fr.ird.observe.entities.seine.TargetLength; import fr.ird.observe.entities.seine.TargetSample; import fr.ird.observe.entities.seine.TripSeine; -import fr.ird.observe.entities.referentiel.Country; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.referentiel.Vessel; -import fr.ird.observe.entities.referentiel.seine.WeightCategory; import fr.ird.observe.test.TestHelper; import org.apache.commons.io.FileUtils; import org.junit.After; @@ -235,7 +234,7 @@ public class ReplicationServiceTest { @Test public void replicateReferentiel() throws Exception { - ReplicationService service = ObserveServiceHelper.newReplicationService(); + ReplicationService service = new ReplicationService(); service.replicateReferentiel(localSource, dstSource); @@ -265,7 +264,7 @@ public class ReplicationServiceTest { @Test public void replicateData() throws Exception { - ReplicationService service = ObserveServiceHelper.newReplicationService(); + ReplicationService service = new ReplicationService(); service.replicateReferentiel(localSource, dstSource); diff --git a/observe-business/src/test/java/fr/ird/observe/its/migration/H2DataSourceMigrationIT.java b/observe-business/src/test/java/fr/ird/observe/its/migration/H2DataSourceMigrationIT.java index 793f752..df46597 100644 --- a/observe-business/src/test/java/fr/ird/observe/its/migration/H2DataSourceMigrationIT.java +++ b/observe-business/src/test/java/fr/ird/observe/its/migration/H2DataSourceMigrationIT.java @@ -23,8 +23,6 @@ package fr.ird.observe.its.migration; import com.google.common.base.Function; import com.google.common.collect.Maps; -import fr.ird.observe.DataService; -import fr.ird.observe.ObserveServiceHelper; import fr.ird.observe.db.DBTestHelper; import fr.ird.observe.db.impl.H2DataSource; import fr.ird.observe.db.impl.H2DataSourceConfig; @@ -116,9 +114,7 @@ public class H2DataSourceMigrationIT extends AbstractDataSourceMigrationTest<H2D Assert.assertNotNull("could not find resource : " + csvFilepath, dbUrl); - DataService dataService = ObserveServiceHelper.get().getDataService(); - - List<Species> speciesList = dataService.getList(service, Species.class); + List<Species> speciesList = DBTestHelper.getList(service, Species.class, null); SpeciesImportModel importModel = new SpeciesImportModel(speciesList); diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/AbstractReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/AbstractReportIT.java index a453d50..54fbb1e 100644 --- a/observe-business/src/test/java/fr/ird/observe/its/report/AbstractReportIT.java +++ b/observe-business/src/test/java/fr/ird/observe/its/report/AbstractReportIT.java @@ -125,7 +125,7 @@ public abstract class AbstractReportIT { ); // recuperation de la maree a utiliser - List<TripSeine> marees = ObserveServiceHelper.getDataService().getList(dataSource, TripSeine.class); + List<TripSeine> marees = DBTestHelper.getList(dataSource, TripSeine.class, null); Assert.assertFalse("No maree found in " + dataSource.getLabel(), marees.isEmpty()); Assert.assertEquals("Should have found exactly one maree, but was " + marees.size(), 1, marees.size()); diff --git a/observe-entities/src/main/java/fr/ird/observe/entities/OpenableEntities.java b/observe-entities/src/main/java/fr/ird/observe/entities/OpenableEntities.java index a3cb922..a78b2a3 100644 --- a/observe-entities/src/main/java/fr/ird/observe/entities/OpenableEntities.java +++ b/observe-entities/src/main/java/fr/ird/observe/entities/OpenableEntities.java @@ -22,12 +22,6 @@ package fr.ird.observe.entities; * #L% */ -import fr.ird.observe.ObserveDAOHelper; -import fr.ird.observe.entities.seine.TripSeine; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaRuntimeException; - import java.util.Collection; /** @@ -38,72 +32,75 @@ import java.util.Collection; */ public class OpenableEntities { - /** - * @param o l'objet dont on veut tester le type - * @return {@code true} si l'objet est non null et de type {@link - * OpenableEntity}, {@code false} autrement. - */ - public static boolean isOpenable(Object o) { - if (o == null) { - return false; - } - Class<?> c; - if (!Class.class.equals(o.getClass())) { - c = o.getClass(); - } else { - c = (Class<?>) o; - } - return OpenableEntity.class.isAssignableFrom(c); - } +// /** +// * @param o l'objet dont on veut tester le type +// * @return {@code true} si l'objet est non null et de type {@link +// * OpenableEntity}, {@code false} autrement. +// */ +// public static boolean isOpenable(Object o) { +// if (o == null) { +// return false; +// } +// Class<?> c; +// if (!Class.class.equals(o.getClass())) { +// c = o.getClass(); +// } else { +// c = (Class<?>) o; +// } +// return OpenableEntity.class.isAssignableFrom(c); +// } - /** - * //FIXME Should use also a getOpenTrip for Longline model. - * @param ctxt le topia context - * @return la marée ouverte, ou <code>null</code> si pas de marée ouverte - * @throws TopiaException if any pb - */ - public static TripSeine getOpenTrip(TopiaContext ctxt) throws TopiaException { - if (ctxt == null) { - throw new TopiaRuntimeException("could not find a local topia" + - " context"); - } - TripSeine m = ObserveDAOHelper.getTripSeineDAO(ctxt).findByOpen(true); - return m; - } +// /** +// * //FIXME Should use also a getOpenTrip for Longline model. +// * @param ctxt le topia context +// * @return la marée ouverte, ou <code>null</code> si pas de marée ouverte +// * @throws TopiaException if any pb +// */ +// public static TripSeine getOpenTrip(TopiaContext ctxt) throws TopiaException { +// if (ctxt == null) { +// throw new TopiaRuntimeException("could not find a local topia context"); +// } +// TripSeine m = ObserveDAOHelper.getTripSeineDAO(ctxt).findByOpen(true); +// return m; +// } - /** - * @param <O> le type des données de type {@link OpenableEntity} - * @param openableEntity l'openableEntity ou rechercher dans ses chils - * @return l'objet dans la liste qui est ouvert, ou <code>null</code> si - * aucun objet ouvert. - */ - public static <O extends OpenableEntity> O getOpenChild(OpenableEntity openableEntity) { - Collection<?> openables = openableEntity.getOpenableChilds(); - if (openables != null) { - for (Object o : openables) { - if (((OpenableEntity) o).isOpen()) { - return (O) o; - } - } - } - return null; - } +// /** +// * @param <O> le type des données de type {@link OpenableEntity} +// * @param openableEntity l'openableEntity ou rechercher dans ses chils +// * @return l'objet dans la liste qui est ouvert, ou <code>null</code> si +// * aucun objet ouvert. +// */ +// public static <O extends OpenableEntity> O getOpenChild(OpenableEntity openableEntity) { +// Collection<?> openables = openableEntity.getOpenableChilds(); +// if (openables != null) { +// for (Object o : openables) { +// if (((OpenableEntity) o).isOpen()) { +// return (O) o; +// } +// } +// } +// return null; +// } /** * @param <O> le type des données de type {@link OpenableEntity} * @param openables une liste de données de type {@link OpenableEntity}. - * @return l'objet dans la liste qui est ouvert, ou <code>null</code> si - * aucun objet ouvert. + * @return l'objet dans la liste qui est ouvert, ou <code>null</code> si aucun objet ouvert. */ - public static <O extends OpenableEntity> O getOpenEntity( - Collection<O> openables) { + public static <O extends OpenableEntity> O getOpenEntity(Collection<O> openables) { + + O result = null; + if (openables != null) { for (O o : openables) { if (o.isOpen()) { - return o; + result = o; + break; } } } - return null; + + return result; + } } diff --git a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParameterDAOImpl.java b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParameterDAOImpl.java index d079a72..cb2c3e3 100644 --- a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParameterDAOImpl.java +++ b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParameterDAOImpl.java @@ -1,4 +1,36 @@ package fr.ird.observe.entities.referentiel; +import org.nuiton.topia.TopiaException; + +import java.util.Iterator; +import java.util.List; + public class LengthWeightParameterDAOImpl<E extends LengthWeightParameter> extends LengthWeightParameterDAOAbstract<E> { + + public List<E> findAllBySpecies(Species species) throws TopiaException { + + List<E> list = findAllByProperties(LengthWeightParameter.PROPERTY_SPECIES, species); + + // on supprime les paramétrages qui ont a=0 ou a=null ou b=0 ou b = null + Iterator<E> itr = list.iterator(); + while (itr.hasNext()) { + E p = itr.next(); + Double a = p.getCoefficientValue(LengthWeightParemeterHelper.COEFFICIENT_A); + if (a == null || a == 0) { + itr.remove(); + continue; + } + + Double b = p.getCoefficientValue(LengthWeightParemeterHelper.COEFFICIENT_B); + // on autorise d'avoir b à 0 (mais cela ne permet plus de calculer la taille à partir du poids) +// if (b == null || b == 0) { + if (b == null) { + itr.remove(); + } + } + + return list; + + } + } diff --git a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParemeterHelper.java b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParemeterHelper.java index cb5655d..1b82c47 100644 --- a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParemeterHelper.java +++ b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/LengthWeightParemeterHelper.java @@ -68,9 +68,9 @@ public class LengthWeightParemeterHelper { /** variable taille à utiliser dans la relation weight */ public static final String VARIABLE_TAILLE = "L"; - private static final String COEFFICIENT_A = "a"; + public static final String COEFFICIENT_A = "a"; - private static final String COEFFICIENT_B = "b"; + public static final String COEFFICIENT_B = "b"; protected static ScriptEngine getScriptEngine() { if (scriptEngine == null) { diff --git a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/ReferenceEntities.java b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/ReferenceEntities.java index 35ff744..2825219 100644 --- a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/ReferenceEntities.java +++ b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/ReferenceEntities.java @@ -95,7 +95,7 @@ public class ReferenceEntities { } }; - public static void walk(ReferentielWalker walker) throws Exception { + public static void walk(ReferentielWalker walker) { for (ObserveEntityEnum constant : Entities.REFERENCE_ENTITIES) { Class<? extends TopiaEntity> contractClass = constant.getContract(); walker.walk(contractClass); @@ -116,7 +116,7 @@ public class ReferenceEntities { public interface ReferentielWalker { - <E extends TopiaEntity> void walk(Class<E> beanClass) throws Exception; + <E extends TopiaEntity> void walk(Class<E> beanClass) ; } } diff --git a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/SexDAOImpl.java b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/SexDAOImpl.java index 97f220e..c5c8e92 100644 --- a/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/SexDAOImpl.java +++ b/observe-entities/src/main/java/fr/ird/observe/entities/referentiel/SexDAOImpl.java @@ -1,7 +1,11 @@ package fr.ird.observe.entities.referentiel; -import javax.annotation.Generated; - -@Generated(value = "org.nuiton.topia.generator.EntityDAOTransformer", date = "Sat May 02 12:01:39 CEST 2015") public class SexDAOImpl<E extends Sex> extends SexDAOAbstract<E> { -} //SexDAOImpl<E extends Sex> + + public E getUnknownSex() { + + E sex = findByCode("fr.ird.observe.entities.referentiel.Sex#1239832686121#0.0"); + return sex; + + } +} diff --git a/observe-services/src/main/java/fr/ird/observe/services/AbstractObserveService.java b/observe-services/src/main/java/fr/ird/observe/services/AbstractObserveService.java index 127fd89..f7dab53 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/AbstractObserveService.java +++ b/observe-services/src/main/java/fr/ird/observe/services/AbstractObserveService.java @@ -6,6 +6,7 @@ import com.google.common.collect.Lists; import fr.ird.observe.BinderService; import fr.ird.observe.IObserveConfig; import fr.ird.observe.ObserveEntityEnum; +import fr.ird.observe.db.DataSource; import fr.ird.observe.entities.Entities; import fr.ird.observe.entities.EntityMap; import fr.ird.observe.entities.constants.ReferenceLocale; @@ -48,7 +49,7 @@ public abstract class AbstractObserveService implements ObserveService { @Override public <E extends TopiaEntity> EntityMap findAllUsages(E entity) { - Class<E> entityType = (Class<E>) ObserveEntityEnum.valueOf(entity).getContract(); + Class<E> entityType = getEntityContractClass(entity); TopiaDAO<E> dao = getDao(entityType); @@ -79,7 +80,7 @@ public abstract class AbstractObserveService implements ObserveService { if (Entities.isDataClass(klass)) { // on verifie que l'on a le droit de lire la donnee - if (!serviceContext.getDataSource().canReadData()) { + if (!getDataSource().canReadData()) { if (log.isDebugEnabled()) { log.debug("Can not read data, no read credential"); } @@ -89,7 +90,7 @@ public abstract class AbstractObserveService implements ObserveService { if (Entities.isReferentielClass(klass)) { // on verifie que l'on a le droit de lire la donnee - if (!serviceContext.getDataSource().canReadReferentiel()) { + if (!getDataSource().canReadReferentiel()) { if (log.isDebugEnabled()) { log.debug("Can not read referentiel, no read credential"); } @@ -151,13 +152,22 @@ public abstract class AbstractObserveService implements ObserveService { return getBinderService().getBinder(entityClass, contextName); } + protected <E extends TopiaEntity> TopiaDAO<E> getDao(E entity) { + Class<E> entityType = getEntityContractClass(entity); + return getDataSource().getDAO(getTransaction(), entityType); + } + + protected DataSource getDataSource() { + return serviceContext.getDataSource(); + } + protected <E extends TopiaEntity> TopiaDAO<E> getDao(Class<E> entityType) { - return serviceContext.getDataSource().getDAO(getTransaction(), entityType); + return getDataSource().getDAO(getTransaction(), entityType); } protected <E extends TopiaEntity> E findByTopiaId(Class<E> entityType, String topiaId) { - TopiaDAO<E> dao = serviceContext.getDataSource().getDAO(getTransaction(), entityType); + TopiaDAO<E> dao = getDataSource().getDAO(getTransaction(), entityType); return dao.findByTopiaId(topiaId); } @@ -183,6 +193,18 @@ public abstract class AbstractObserveService implements ObserveService { } + protected <E extends TopiaEntity> String decorateEntity(E entity) { + + Class<E> entityType = getEntityContractClass(entity); + Decorator<E> decorator = getDecoratorByType(entityType, null); + return decorator.toString(entity); + + } + + protected <E extends TopiaEntity> Class<E> getEntityContractClass(E entity) { + return (Class<E>) ObserveEntityEnum.valueOf(entity).getContract(); + } + protected <E extends TopiaEntity> List<E> getList0(Class<E> klass, Predicate<E> predicate) { TopiaDAO<E> dao = getDao(klass); @@ -199,7 +221,7 @@ public abstract class AbstractObserveService implements ObserveService { } - public <P extends TopiaEntity, E extends TopiaEntity> String doSave(String parentId, E toSave, SaveAction<P, E> saveAction) { + protected <P extends TopiaEntity, E extends TopiaEntity> String doSave(String parentId, E toSave, SaveAction<P, E> saveAction) { E saved; saveAction.beforeSave(parentId, toSave); @@ -268,7 +290,7 @@ public abstract class AbstractObserveService implements ObserveService { } - public <P extends TopiaEntity, E extends TopiaEntity> void doDelete(String parentId, String idToDelete, DeleteAction<P, E> deleteAction) { + protected <P extends TopiaEntity, E extends TopiaEntity> void doDelete(String parentId, String idToDelete, DeleteAction<P, E> deleteAction) { P parent = null; @@ -290,7 +312,6 @@ public abstract class AbstractObserveService implements ObserveService { getDao(deleteAction.parentClass).update(parent); } - } protected class DeleteAction<P extends TopiaEntity, E extends TopiaEntity> { @@ -310,7 +331,7 @@ public abstract class AbstractObserveService implements ObserveService { } - public <P extends TopiaEntity, E extends TopiaEntity> void doSaveList(P parentToSave, SaveCollectionAction<P, E> saveCollectionAction) { + protected <P extends TopiaEntity, E extends TopiaEntity> void doSaveList(P parentToSave, SaveCollectionAction<P, E> saveCollectionAction) { Collection<E> childrenToSave = saveCollectionAction.listUpdator.getChilds(parentToSave); @@ -415,12 +436,12 @@ public abstract class AbstractObserveService implements ObserveService { } - public <E extends TopiaEntity> void checkNotNullAndNoneExistingEntity(String variableName, E entity) { + protected <E extends TopiaEntity> void checkNotNullAndNoneExistingEntity(String variableName, E entity) { TopiaEntityHelper.checkNotNullAndNoneExistingEntity(variableName, entity); } - public <E extends TopiaEntity> void checkNotNullAndExistingEntity(String variableName, E entity) { + protected <E extends TopiaEntity> void checkNotNullAndExistingEntity(String variableName, E entity) { TopiaEntityHelper.checkNotNullAndExistingEntity(variableName, entity); } @@ -431,5 +452,12 @@ public abstract class AbstractObserveService implements ObserveService { } + protected ObserveServiceFactory newServiceFactory(DataSource dataSource) { + + ObserveServiceFactory serviceFactory = ObserveServiceFactory.newFactory(serviceContext.applicationContext, dataSource); + return serviceFactory; + + } + } diff --git a/observe-services/src/main/java/fr/ird/observe/services/ReplicationService.java b/observe-services/src/main/java/fr/ird/observe/services/ReplicationService.java index 865a5c5..1a4d3cf 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/ReplicationService.java +++ b/observe-services/src/main/java/fr/ird/observe/services/ReplicationService.java @@ -1,11 +1,32 @@ package fr.ird.observe.services; +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.db.DataSource; +import fr.ird.observe.db.DataSourceException; +import org.nuiton.topia.persistence.TopiaEntity; + +import java.util.List; + /** * Created on 5/3/15. * * @author Tony Chemit - chemit@codelutin.com - * @since XXX + * @since 4.0 */ -public interface ReplicationService { +public interface ReplicationService extends ObserveService{ + + @Commit + void replicateObsoletesEntities(List<TopiaEntity> obsoleteEntities, DataSource source, SendMessageAble messanger) throws DataSourceException; + + @Commit + void replicateReferentiel(DataSource srcService) throws DataSourceException; + + @Commit + void replicateReferentiel(DataSource srcService, List<String> ids, SendMessageAble messanger) throws DataSourceException; + + @Commit + void replicateAllData(DataSource srcService) throws DataSourceException; + @Commit + void replicateData(DataSource srcService, String... ids) throws DataSourceException; } diff --git a/observe-services/src/main/java/fr/ird/observe/services/ReplicationServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/ReplicationServiceImpl.java index dcac5bc..d64ddc3 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/ReplicationServiceImpl.java +++ b/observe-services/src/main/java/fr/ird/observe/services/ReplicationServiceImpl.java @@ -1,11 +1,423 @@ package fr.ird.observe.services; +import fr.ird.observe.DecoratorService; +import fr.ird.observe.ObserveDAOHelper; +import fr.ird.observe.ObserveEntityEnum; +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.db.DataSource; +import fr.ird.observe.db.DataSourceException; +import fr.ird.observe.db.constants.DataSourceState; +import fr.ird.observe.entities.Entities; +import fr.ird.observe.entities.Trip; +import fr.ird.observe.entities.longline.TripLongline; +import fr.ird.observe.entities.longline.TripLonglines; +import fr.ird.observe.entities.seine.TripSeineDAO; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.tuple.Pair; +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.framework.TopiaSQLQuery; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.replication.TopiaReplicationService; +import org.nuiton.topia.replication.model.ReplicationModel; +import org.nuiton.util.StringUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + /** * Created on 5/3/15. * * @author Tony Chemit - chemit@codelutin.com - * @since XXX + * @since 4.0 */ -public class ReplicationServiceImpl implements ReplicationService { +public class ReplicationServiceImpl extends AbstractObserveService implements ReplicationService { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ReplicationServiceImpl.class); + + @Override + public void replicateObsoletesEntities(List<TopiaEntity> obsoleteEntities, DataSource source, SendMessageAble messanger) throws DataSourceException { + + String txName = "replicateObsoletesEntities"; + TopiaContext sourceCtxt = source.beginTransaction(txName); + try { + + for (ObserveEntityEnum constant : Entities.REFERENCE_ENTITIES) { + + Class<? extends TopiaEntity> contractClass = constant.getContract(); + List<TopiaEntity> toReplicate = new ArrayList<TopiaEntity>(); + for (Iterator<TopiaEntity> itr = obsoleteEntities.iterator(); itr.hasNext(); ) { + + TopiaEntity e = itr.next(); + if (contractClass.isAssignableFrom(e.getClass())) { + if (log.isDebugEnabled()) { + log.debug("obsolete to inject : " + e.getTopiaId()); + } + itr.remove(); + + // cet objet doit etre replique + toReplicate.add(e); + + messanger.sendMessage(t("observe.message.synchro.obsolete.data.to.duplicate", e)); + } + } + + if (toReplicate.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("no obsolete entity " + constant); + } + continue; + } + + if (log.isDebugEnabled()) { + log.debug("inject obsolete entity " + constant + " (" + toReplicate.size() + ")"); + } + + sourceCtxt.replicateEntities(getTransaction(), toReplicate); + + getTransaction().commitTransaction(); + + } + + } finally { + + source.closeTransaction(sourceCtxt, txName); + + } + + if (!obsoleteEntities.isEmpty()) { + throw new IllegalStateException("there is still obsolete entities to inject in synchro db : " + obsoleteEntities); + } + + } + + /** + * Duplication du référentiel depuis la source donnée en paramètre vers la source de ce service. + * + * @param srcService le service source qui contient les référentiels à repliquer + * @throws DataSourceException if pb + */ + public void replicateReferentiel(DataSource srcService) throws DataSourceException { + + if (srcService == null) { + throw new NullPointerException("srcService can not be null"); + } + + srcService.checkState(DataSourceState.OPEN); + + if (srcService.equals(getDataSource())) { + throw new IllegalArgumentException("can not duplicate to the same service..."); + } + long t0 = System.nanoTime(); + + Date date = new Date(); + srcService.fireNewMessage(t("observe.storage.message.replicate.referentiel.starting", date)); + + try { + + TopiaReplicationService service = srcService.getTopiaService(TopiaReplicationService.class); + + ReplicationModel model = service.prepareForAll(Entities.REFERENCE_ENTITIES); + + service.doReplicate(model, getTransaction()); + + String delay = StringUtil.convertTime(t0, System.nanoTime()); + srcService.fireNewMessage( + t("observe.storage.message.replicate.referentiel.done", delay)); + } catch (Exception e) { + throw new DataSourceException(e, "replicateReferentiel"); + } + } + + @Override + public void replicateReferentiel(DataSource srcService, List<String> ids, SendMessageAble messanger) throws DataSourceException { + + for (String id : ids) { + + String txName = "replicateReferentiel::" + id; + TopiaContext tx = srcService.beginTransaction(txName); + + try { + + TopiaEntity entity = tx.findByTopiaId(id); + String message = t("observe.synchro.add.object", id); + messanger.sendMessage(message); + tx.replicateEntity(getTransaction(), entity); + + // On est obligé de commiter à chaque ajout sinon si + // une autre entité à ajouter depend de celle là, on + // ne la retrouve pas + getTransaction().commitTransaction(); + if (log.isDebugEnabled()) { + log.debug("add [" + id + "] : "); + } + + } finally { + + // rollback context since we do not want to keep any modification + try { + srcService.rollbackTransaction(tx, txName); + } finally { + srcService.closeTransaction(tx, txName); + } + + } + + } + + } + + /** + * Duplication de toutes les données depuis le service passé en paramètre. + * + * @param srcService le service source + * @throws DataSourceException if pb + */ + public void replicateAllData(DataSource srcService) throws DataSourceException { + + srcService.checkState(DataSourceState.OPEN); + + // le service peut-être en cours d'ouverture + getDataSource().checkState(DataSourceState.INIT, DataSourceState.OPEN); + + if (srcService.equals(getDataSource())) { + throw new IllegalArgumentException("can not replcate to the same service..."); + } + + // recuperation des marees a repliquer + + String[] topiaIds = null; + + TopiaContext srcCtxt = srcService.beginTransaction("replicateData"); + try { + + TripSeineDAO srcTripDAO = ObserveDAOHelper.getTripSeineDAO(srcCtxt); + List<String> allIds = srcTripDAO.findAllIds(); + + if (CollectionUtils.isEmpty(allIds)) { + + // aucune donnee a repliquer + srcService.fireNewMessage(t("observe.storage.message.replicate.data.no.data")); + return; + + } + + topiaIds = allIds.toArray(new String[allIds.size()]); + + } catch (TopiaException e) { + + throw new DataSourceException(e, "replicateData"); + + } finally { + + // rollback context since we do not want to keep any modification + try { + srcService.rollbackTransaction(srcCtxt, "replicateData"); + } finally { + srcService.closeTransaction(srcCtxt, "replicateData"); + } + + } + + // replication des marees + replicateData(srcService, topiaIds); + + } + + /** + * Duplication de données observateur depuis la source passée en paramètre. + * + * @param srcService le service source + * @param ids les ids des entités à répliquer + * @throws DataSourceException if pb + */ + public void replicateData(DataSource srcService, String... ids) throws DataSourceException { + + if (srcService == null) { + throw new NullPointerException("srcService can not be null"); + } + + srcService.checkState(DataSourceState.OPEN); + // le service peut-être en cours d'ouverture + getDataSource().checkState(DataSourceState.INIT, DataSourceState.OPEN); + + if (srcService.equals(getDataSource())) { + throw new IllegalArgumentException("can not replcate to the same service..."); + } + + long t0 = System.nanoTime(); + + srcService.fireNewMessage(t("observe.storage.message.replicate.entities.starting", now())); + + for (String id : ids) { + replicateOneData(srcService, id); + } + + String time = StringUtil.convertTime(t0, System.nanoTime()); + srcService.fireNewMessage(t("observe.storage.message.replicate.entities.done", time)); + + } + + /** + * Duplication de l'unique donnée observateur depuis ce service vers le service donné. + * <p/> + * La duplication utilise une transaction dédiée afin de ne pas saturer le serveur + * et aussi une meilleure maitrise du rollback en cas d'une erreur. + * <p/> + * Voir http://forge.codelutin.com/issues/4837 + * + * @param srcService le service source + * @param id les ids des entités à répliquer + * @throws DataSourceException if pb + */ + protected void replicateOneData(DataSource srcService, String id) throws DataSourceException { + + String dstLabel = getDataSource().getShortLabel(); + + TopiaReplicationService service = srcService.getTopiaService(TopiaReplicationService.class); + + ReplicationModel model; + try { + model = service.prepare(Entities.DATA_ENTITIES, false, id); + } catch (TopiaException e) { + throw new DataSourceException(e, "replicateData"); + } + + // To fix missing tdr associations (see https://forge.codelutin.com/issues/6611) + List<Pair<String, String>> tdrAssociation = null; + + TopiaContext srcCtxt = srcService.beginTransaction("replicateData"); + try { + + TopiaEntity e = srcCtxt.findByTopiaId(id); + String label = t(DecoratorService.getEntityLabel(e.getClass())) + " :: " + id; + srcService.fireNewMessage(t("observe.storage.message.replicate.data.entity", label, dstLabel)); + + if (e instanceof Trip && Entities.isLonglineId(id)) { + + // Grab tdr missing associations (see https://forge.codelutin.com/issues/6611) + if (log.isInfoEnabled()) { + log.info("Should keep SetLongline - Tdr association ids for: " + id); + } + + tdrAssociation = getTdrAssociationIds(srcCtxt, (TripLongline) e); + + } + } catch (TopiaException e) { + throw new DataSourceException(e, "replicateData"); + } finally { + srcService.closeTransaction(srcCtxt, "replicateData"); + } + + TopiaContext dstCtxt = getTransaction(); + try { + + // do the replicate + service.doReplicate(model, dstCtxt); + + // Apply back tdr missing associations (see https://forge.codelutin.com/issues/6611) + applyTdrAssociationFix(dstCtxt, tdrAssociation); + + // commit the result + getTransaction().commitTransaction(); + + } catch (Exception e) { + getTransaction().rollbackTransaction(); + throw new DataSourceException(e, "replicateData"); + } finally { + + getTransaction().rollbackTransaction(); + + } + + } + + private void applyTdrAssociationFix(TopiaContext dstCtxt, List<Pair<String, String>> tdrAssociation) throws TopiaException { + + String request = "\nUPDATE OBSERVE_LONGLINE.TDR SET SET = '%s' WHERE topiaid = '%s';"; + + StringBuilder builder = new StringBuilder(); + + if (CollectionUtils.isNotEmpty(tdrAssociation)) { + for (Pair<String, String> entry : tdrAssociation) { + builder.append(String.format(request, entry.getKey(), entry.getValue())); + } + } + + dstCtxt.executeSQL(builder.toString()); + + } + + private List<Pair<String, String>> getTdrAssociationIds(TopiaContext srcCtxt, TripLongline e) throws TopiaException { + + List<Pair<String, String>> result = new ArrayList<Pair<String, String>>(); + + Set<String> setIds = TripLonglines.getSetIdsWithTdr(e); + + GetTdrIdsQuery query = new GetTdrIdsQuery(); + + for (String setId : setIds) { + + List<Pair<String, String>> multipleResult = query.execute((TopiaContextImplementor) srcCtxt, setId); + + if (log.isDebugEnabled()) { + log.debug("Found TDR associations: " + multipleResult); + } + result.addAll(multipleResult); + + } + + return result; + } + + + private static class GetTdrIdsQuery extends TopiaSQLQuery<Pair<String, String>> { + + private String setId; + + public List<Pair<String, String>> execute(TopiaContextImplementor tx, String setId) throws TopiaException { + try { + + this.setId = setId; + return findMultipleResult(tx); + + } finally { + + this.setId = null; + + } + } + + @Override + protected PreparedStatement prepareQuery(Connection connection) throws SQLException { + String sql = "SELECT t.SET, t.topiaId " + + "FROM OBSERVE_LONGLINE.TDR t " + + "WHERE t.SET = ?"; + PreparedStatement ps = connection.prepareStatement(sql); + ps.setString(1, setId); + return ps; + } + + @Override + protected Pair<String, String> prepareResult(ResultSet set) throws SQLException { + Pair<String, String> result = + Pair.of(set.getString(1), set.getString(2)); + return result; + } + + } } diff --git a/observe-services/src/main/java/fr/ird/observe/services/data/TripService.java b/observe-services/src/main/java/fr/ird/observe/services/data/TripService.java index 9595f78..9f0933b 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/data/TripService.java +++ b/observe-services/src/main/java/fr/ird/observe/services/data/TripService.java @@ -1,5 +1,6 @@ package fr.ird.observe.services.data; +import fr.ird.observe.entities.Trip; import fr.ird.observe.entities.referentiel.Ocean; import fr.ird.observe.entities.referentiel.Program; import fr.ird.observe.services.Commit; @@ -18,6 +19,8 @@ public interface TripService extends ObserveService { List<Program> getPossibleProgramsForTrip(String tripId); + Trip getTrip(String tripId); + Ocean getTripOcean(String tripId); List<TripMapPoint> loadTripMapActivityPoints(String tripId); diff --git a/observe-services/src/main/java/fr/ird/observe/services/data/TripServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/data/TripServiceImpl.java index 96a740b..d419ecb 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/data/TripServiceImpl.java +++ b/observe-services/src/main/java/fr/ird/observe/services/data/TripServiceImpl.java @@ -28,13 +28,7 @@ public class TripServiceImpl extends AbstractObserveService implements TripServi @Override public List<Program> getPossibleProgramsForTrip(String tripId) { - Trip trip; - - if (tripId.startsWith(TripSeine.class.getSimpleName())) { - trip = findByTopiaId(TripSeine.class, tripId); - } else { - trip = findByTopiaId(TripLongline.class, tripId); - } + Trip trip = getTrip(tripId); GearType gearType = trip.getProgram().getGearType(); @@ -51,7 +45,7 @@ public class TripServiceImpl extends AbstractObserveService implements TripServi } @Override - public Ocean getTripOcean(String tripId) { + public Trip getTrip(String tripId) { Trip trip; @@ -61,6 +55,15 @@ public class TripServiceImpl extends AbstractObserveService implements TripServi trip = findByTopiaId(TripLongline.class, tripId); } + return trip; + + } + + @Override + public Ocean getTripOcean(String tripId) { + + Trip trip = getTrip(tripId); + return trip.getOcean(); } @@ -68,13 +71,7 @@ public class TripServiceImpl extends AbstractObserveService implements TripServi @Override public void moveTripToProgram(String tripId, String programId) { - Trip trip; - - if (tripId.startsWith(TripSeine.class.getName())) { - trip = findByTopiaId(TripSeine.class, tripId); - } else { - trip = findByTopiaId(TripLongline.class, tripId); - } + Trip trip = getTrip(tripId); Program program = findByTopiaId(Program.class, programId); diff --git a/observe-services/src/main/java/fr/ird/observe/services/data/seine/ActivitySeineServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/data/seine/ActivitySeineServiceImpl.java index 6dfb81e..b23bb1b 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/data/seine/ActivitySeineServiceImpl.java +++ b/observe-services/src/main/java/fr/ird/observe/services/data/seine/ActivitySeineServiceImpl.java @@ -129,7 +129,7 @@ public class ActivitySeineServiceImpl extends AbstractObserveService implements ActivitySeine updated = dao.findByTopiaId(toUpdate.getTopiaId()); - copyExcluding(ActivitySeine.class, BinderService.EDIT, toUpdate, updated, true, ActivitySeine.PROPERTY_SET_SEINE); + copy(ActivitySeine.class, BinderService.EDIT_OBSERVED_SYSTEM, toUpdate, updated); if (needUpdateSet) { diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataServiceImpl.java index e56a919..8dab84f 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataServiceImpl.java +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/ComputeDataServiceImpl.java @@ -127,7 +127,7 @@ public class ComputeDataServiceImpl extends AbstractObserveService implements Co @Override public void consolidateTrips(SendMessageAble messager, Set<String> tripIds) { - if (messager==null) { + if (messager == null) { messager = new SendMessageAble() { diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportService.java b/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportService.java index 57770f9..1bf168b 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportService.java +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportService.java @@ -1,11 +1,27 @@ package fr.ird.observe.services.operation; +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.entities.seine.ActivitySeine; +import fr.ird.observe.entities.seine.TripSeine; +import fr.ird.observe.gps.GPSPoint; +import fr.ird.observe.services.Commit; +import fr.ird.observe.services.ObserveService; + +import java.util.Map; + /** * Created on 5/3/15. * * @author Tony Chemit - chemit@codelutin.com - * @since XXX + * @since 4.0 */ -public class GpsImportService { +public interface GpsImportService extends ObserveService { + + TripSeine getOpenTrip(); + + Map<ActivitySeine, GPSPoint> getActivitiesForOpenRoute(String openTripSeineId); + + @Commit + void applyPoints(Map<ActivitySeine, GPSPoint> data, int[] selectedIndex, SendMessageAble messanger); } diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportServiceImpl.java index 5390ca1..4c59cdd 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportServiceImpl.java +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/GpsImportServiceImpl.java @@ -1,11 +1,133 @@ package fr.ird.observe.services.operation; +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.entities.seine.ActivitySeine; +import fr.ird.observe.entities.seine.Route; +import fr.ird.observe.entities.seine.TripSeine; +import fr.ird.observe.entities.seine.TripSeineDAO; +import fr.ird.observe.gps.GPSPoint; +import fr.ird.observe.services.AbstractObserveService; +import org.apache.commons.collections.primitives.ArrayIntList; +import org.apache.commons.collections.primitives.IntIterator; +import org.apache.commons.collections.primitives.IntList; +import org.nuiton.decorator.Decorator; +import org.nuiton.topia.persistence.TopiaDAO; + +import java.util.HashMap; +import java.util.Map; + +import static org.nuiton.i18n.I18n.t; + /** * Created on 5/3/15. * * @author Tony Chemit - chemit@codelutin.com - * @since XXX + * @since 4.0 */ -public class GpsImportServiceImpl implements GpsImportService { +public class GpsImportServiceImpl extends AbstractObserveService implements GpsImportService { + + @Override + public Map<ActivitySeine, GPSPoint> getActivitiesForOpenRoute(String openTripSeineId) { + + Map<ActivitySeine, GPSPoint> data; + + + TripSeine openTripSeine = findByTopiaId(TripSeine.class, openTripSeineId); + + if (openTripSeine.isRouteEmpty()) { + + // pas de route sur la maree ouverte + data = null; + + } else { + + data = new HashMap<ActivitySeine, GPSPoint>(); + + for (Route r : openTripSeine.getRoute()) { + if (!r.isActivitySeineEmpty()) { + // on enregistre les actitives + for (ActivitySeine a : r.getActivitySeine()) { + data.put(a, null); + } + } + } + } + + return data; + + } + + @Override + public void applyPoints(Map<ActivitySeine, GPSPoint> data, int[] selectedIndex, SendMessageAble messanger) { + + Decorator<ActivitySeine> dActivity = getDecoratorByType(ActivitySeine.class, "activity-gps"); + Decorator<GPSPoint> dGPSPoint = getDecoratorByType(GPSPoint.class, "gpsPoint-gps"); + + IntList lIndex = new ArrayIntList(selectedIndex.length); + + for (int i : selectedIndex) { + lIndex.add(i); + } + IntIterator indexItr = lIndex.iterator(); + + int currentActivityIndex = 0; + int nextActivityIndex = indexItr.next(); + + TopiaDAO<ActivitySeine> activityDAO = getDao(ActivitySeine.class); + + for (ActivitySeine a : data.keySet()) { + + if (currentActivityIndex == nextActivityIndex) { + + // l'activité courante a ete selectionne + GPSPoint p = data.get(a); + + messanger.sendMessage(t("observe.message.importGPS.apply.point", dGPSPoint.toString(p), dActivity.toString(a))); +// sendMessage(t("observe.message.importGPS.apply.point", p, a.getVesselActivity().getLabel2())); + float latitude = Math.abs(p.getLatitude()); + float longitude = Math.abs(p.getLongitude()); + int quadrant = p.getQuadrant(); + // application de la position + + ActivitySeine aa = activityDAO.findByTopiaId(a.getTopiaId()); + aa.setLatitude(latitude); + aa.setLongitude(longitude); + aa.setQuadrant(quadrant); + //TODO appliquer la vitesse ? + //a.setVesselSpeed(p.getVitesse()); + + // mise a jour de l'activité + + activityDAO.update(aa); + + if (indexItr.hasNext()) { + + // il reste au moins une activité a traiter + // recuperation du prochain index d'activité a traiter + nextActivityIndex = indexItr.next(); + + } else { + + // plus d'activité a traiter + break; + + } + + } + + currentActivityIndex++; + + } + + } + + @Override + public TripSeine getOpenTrip() { + + TripSeineDAO dao = (TripSeineDAO) getDao(TripSeine.class); + TripSeine openTrip = dao.findByOpen(true); + return openTrip; + + } } diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeService.java b/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeService.java index 8051a13..a1595d2 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeService.java +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeService.java @@ -1,11 +1,38 @@ package fr.ird.observe.services.operation; +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.db.DataSource; +import fr.ird.observe.db.DataSourceException; +import fr.ird.observe.services.Commit; +import fr.ird.observe.services.ObserveService; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.util.DiffState; +import org.nuiton.topia.persistence.util.TopiaEntityRef; + +import java.util.List; +import java.util.SortedMap; + /** + * Pour effectuer la synchronisation des référentiels. + * + * Le service doit être instancié par le service qui veut être mis à jour. Le service qui contient le référentiel à jour + * doit être passé en paramètre. + * * Created on 5/3/15. * * @author Tony Chemit - chemit@codelutin.com - * @since XXX + * @since 4.0 */ -public interface SynchronizeService { +public interface SynchronizeService extends ObserveService { + + DiffState.DiffStateMap buildReferentielDifferentiel(final DataSource centralDataSource, final SendMessageAble messanger); + + SortedMap<TopiaEntity, List<TopiaEntityRef>> detectObsoleteEntities(DiffState.DiffStateMap diff); + + @Commit + void saveReferentiel(DataSource centralDataSource, + DiffState.DiffStateMap diff, + List<ObsoleteReferenceToReplace> replaceActions, + SendMessageAble messanger) throws DataSourceException; } diff --git a/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeServiceImpl.java index ecba6db..e87ec48 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeServiceImpl.java +++ b/observe-services/src/main/java/fr/ird/observe/services/operation/SynchronizeServiceImpl.java @@ -1,11 +1,239 @@ package fr.ird.observe.services.operation; +import fr.ird.observe.DecoratorService; +import fr.ird.observe.ObserveDAOHelper; +import fr.ird.observe.ObserveEntityEnum; +import fr.ird.observe.SendMessageAble; +import fr.ird.observe.db.DataSource; +import fr.ird.observe.db.DataSourceException; +import fr.ird.observe.entities.Entities; +import fr.ird.observe.entities.referentiel.ReferenceEntities; +import fr.ird.observe.entities.seine.TripSeine; +import fr.ird.observe.services.AbstractObserveService; +import fr.ird.observe.services.ObserveServiceFactory; +import fr.ird.observe.services.ReplicationService; +import fr.ird.observe.services.referential.ReferentialService; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.jdbc.Work; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.framework.TopiaContextImplementor; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.util.DiffState; +import org.nuiton.topia.persistence.util.TopiaEntityHelper; +import org.nuiton.topia.persistence.util.TopiaEntityRef; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; + +import static org.nuiton.i18n.I18n.t; + /** + * FIXME Utiliser des pattern Request, Result, Context + * FIXME Ne plus utilisers des messanger + * * Created on 5/3/15. * * @author Tony Chemit - chemit@codelutin.com - * @since XXX + * @since 4.0 */ -public class SynchronizeServiceImpl implements SynchronizeService { +public class SynchronizeServiceImpl extends AbstractObserveService implements SynchronizeService { + + /** Logger. */ + private static final Log log = LogFactory.getLog(SynchronizeServiceImpl.class); + + @Override + public DiffState.DiffStateMap buildReferentielDifferentiel(final DataSource centralDataSource, final SendMessageAble messanger) { + + ObserveServiceFactory centralDataSourceServices = newServiceFactory(centralDataSource); + + try { + + final DiffState.DiffStateMap result = DiffState.newMap(); + + final ReferentialService centralReferentialService = + centralDataSourceServices.getService(ReferentialService.class); + + ReferenceEntities.walk(new ReferenceEntities.ReferentielWalker() { + + + public <E extends TopiaEntity> void walk(Class<E> contractClass) { + + String s = t(DecoratorService.getEntityLabel(contractClass)); + String message = + t("observe.service.build.synchro.referentiel", s); + if (messanger != null) { + messanger.sendMessage(message); + } + if (log.isInfoEnabled()) { + log.info(message); + } + List<E> list = centralReferentialService.getList(contractClass); + List<E> list2 = getList(contractClass); + DiffState.DiffStateMap tmp; + // recuperation du differentiel pour le type d'entitétmp = + tmp = TopiaEntityHelper.buildDifferentiel(list, list2); + // ajout au resultat + DiffState.addAll(result, tmp); + // on nettoie + DiffState.clear(tmp); + } + }); + DiffState.removeEmptyStates(result); + return result; + + } finally { + + centralDataSourceServices.close(); + + } + + } + + @Override + public SortedMap<TopiaEntity, List<TopiaEntityRef>> detectObsoleteEntities(DiffState.DiffStateMap diff) { + + // detection des entites obsoletes + + List<String> removedList = diff.get(DiffState.REMOVED); + + String[] ids = removedList.toArray(new String[removedList.size()]); + + // detection des entites obsoletes + + // des suppressions ont ete detectees, on doit retrouver + // dans la base locale les entites utilisant ces entites obsoletes + List<TripSeine> marees = getDao(TripSeine.class).findAll(); + + ObserveEntityEnum[] contracts = ObserveDAOHelper.getContracts(); + + SortedMap<TopiaEntity, List<TopiaEntityRef>> result; + + result = TopiaEntityHelper.detectReferences(contracts, ids, marees); + return result; + + } + + @Override + public void saveReferentiel(DataSource centralDataSource, + DiffState.DiffStateMap diff, + List<ObsoleteReferenceToReplace> obsoleteReferencesToReplace, + SendMessageAble messanger) throws DataSourceException { + + Map<TopiaEntity, Long> versionsToUpdate = new HashMap<TopiaEntity, Long>(); + + List<String> ids; + + ObserveServiceFactory centralSourceFactory = newServiceFactory(centralDataSource); + + try { + + // ajout des nouvelles entites du referentiel + + ids = diff.get(DiffState.NEW); + if (CollectionUtils.isNotEmpty(ids)) { + + ReplicationService replicationService = newService(ReplicationService.class); + + replicationService.replicateReferentiel(centralDataSource, ids, messanger); + + } + + ReferentialService localReferentialService = newService(ReferentialService.class); + + // mis a jour des entites modifiees + + ids = diff.get(DiffState.MODIFIED); + if (CollectionUtils.isNotEmpty(ids)) { + + ReferentialService service = centralSourceFactory.getService(ReferentialService.class); + Collection<? extends TopiaEntity> entitiesToCopy = service.loadSimpleEntities(ids); + + localReferentialService.copySimpleEntities(entitiesToCopy); + + } + + // mise à jour des données utilisateurs (remplacements d'objets obsolètes) + + for (ObsoleteReferenceToReplace referenceToReplace : obsoleteReferencesToReplace) { + + String message = t("observe.synchro.replaceObsolete.object", referenceToReplace.getObsoleteId()); + messanger.sendMessage(message); + + localReferentialService.replaceObsoleteReference(referenceToReplace); + + } + + // si on ne commite pas ici, les modifications utilisateurs sont perdues + getTransaction().commitTransaction(); + + // suppression des entités obsoletes de la base source + + ids = diff.get(DiffState.REMOVED); + if (CollectionUtils.isNotEmpty(ids)) { + + localReferentialService.deleteEntities(ids); + + } + + if (MapUtils.isNotEmpty(versionsToUpdate)) { + + // on applique le patch sur les versions pour bien avoir + // la bonne version de topiaversion et pas seulement un incrément + // de 1 puisque ce champs est géré par hibernate et qu'il ne nous laisse + // pas la possibilité de choisir la valeur qu'on veut attribuer au champs... + patchTopiaVersions(versionsToUpdate); + } + + getTransaction().commitTransaction(); + + } finally { + + centralSourceFactory.close(); + + } + } + + private static final String UPDATE_VERSION_PATTERN = "UPDATE %1$s SET topiaversion = %2$d WHERE topiaid='%3$s';\n"; + + protected void patchTopiaVersions(Map<TopiaEntity, Long> versionsToUpdate) throws TopiaException { + + final StringBuilder buffer = new StringBuilder(); + + for (Map.Entry<TopiaEntity, Long> entry : + versionsToUpdate.entrySet()) { + TopiaEntity entity = entry.getKey(); + String id = entity.getTopiaId(); + Long version = entry.getValue(); + String tableName = Entities.getTableName(entity); + buffer.append(String.format(UPDATE_VERSION_PATTERN, tableName, version, id)); + + } + ((TopiaContextImplementor) getTransaction()).getHibernate().doWork(new Work() { + + @Override + public void execute(Connection connection) throws SQLException { + String sql = buffer.toString(); + PreparedStatement sta = connection.prepareStatement(sql); + try { + if (log.isDebugEnabled()) { + log.debug("Will execute sql code :\n" + sql); + } + sta.executeUpdate(); + } finally { + sta.close(); + } + } + }); + } + } diff --git a/observe-services/src/main/java/fr/ird/observe/services/referential/ReferentialService.java b/observe-services/src/main/java/fr/ird/observe/services/referential/ReferentialService.java index 654a379..3349da2 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/referential/ReferentialService.java +++ b/observe-services/src/main/java/fr/ird/observe/services/referential/ReferentialService.java @@ -1,12 +1,20 @@ package fr.ird.observe.services.referential; +import fr.ird.observe.ObserveTechnicalException; +import fr.ird.observe.entities.referentiel.LengthWeightParameter; +import fr.ird.observe.entities.referentiel.Ocean; import fr.ird.observe.entities.referentiel.Program; import fr.ird.observe.entities.referentiel.ReferenceEntity; +import fr.ird.observe.entities.referentiel.Sex; import fr.ird.observe.entities.referentiel.Species; import fr.ird.observe.entities.referentiel.seine.WeightCategory; import fr.ird.observe.services.Commit; import fr.ird.observe.services.ObserveService; +import fr.ird.observe.services.operation.ObsoleteReferenceToReplace; +import org.nuiton.topia.persistence.TopiaEntity; +import java.util.Collection; +import java.util.Date; import java.util.List; import java.util.Set; @@ -38,6 +46,13 @@ public interface ReferentialService extends ObserveService { Set<String> getSpeciesListSpeciesIds(String speciesListId); + LengthWeightParameter findLengthWeightParameter(Species species, Ocean ocean, Sex sex, Date date) throws ObserveTechnicalException; + + Collection<? extends TopiaEntity> loadSimpleEntities(Collection<String> entityIds); + + @Commit + void copySimpleEntities(Collection<? extends TopiaEntity> entities); + <R extends ReferenceEntity> R preCreate(Class<R> entityType); @Commit @@ -45,4 +60,11 @@ public interface ReferentialService extends ObserveService { @Commit <R extends ReferenceEntity> void delete(Class<R> entityType, String referentialId); + + @Commit + void deleteEntities(Collection<String> entityIds); + + @Commit + void replaceObsoleteReference(ObsoleteReferenceToReplace action); + } diff --git a/observe-services/src/main/java/fr/ird/observe/services/referential/ReferentialServiceImpl.java b/observe-services/src/main/java/fr/ird/observe/services/referential/ReferentialServiceImpl.java index fa3c99a..0202565 100644 --- a/observe-services/src/main/java/fr/ird/observe/services/referential/ReferentialServiceImpl.java +++ b/observe-services/src/main/java/fr/ird/observe/services/referential/ReferentialServiceImpl.java @@ -4,23 +4,39 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; import fr.ird.observe.BinderService; import fr.ird.observe.ObserveEntityEnum; +import fr.ird.observe.ObserveTechnicalException; import fr.ird.observe.entities.constants.ReferenceLocale; import fr.ird.observe.entities.constants.ReferenceStatus; import fr.ird.observe.entities.referentiel.LengthWeightParameter; +import fr.ird.observe.entities.referentiel.LengthWeightParameterDAO; +import fr.ird.observe.entities.referentiel.LengthWeightParemeterHelper; +import fr.ird.observe.entities.referentiel.Ocean; import fr.ird.observe.entities.referentiel.Program; import fr.ird.observe.entities.referentiel.ProgramDAO; import fr.ird.observe.entities.referentiel.Programs; import fr.ird.observe.entities.referentiel.ReferenceEntity; +import fr.ird.observe.entities.referentiel.Sex; +import fr.ird.observe.entities.referentiel.SexDAO; import fr.ird.observe.entities.referentiel.Species; import fr.ird.observe.entities.referentiel.SpeciesList; import fr.ird.observe.entities.referentiel.seine.WeightCategory; import fr.ird.observe.services.AbstractObserveService; +import fr.ird.observe.services.operation.ObsoleteReferenceToReplace; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.jxpath.JXPathContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.nuiton.decorator.Decorator; +import org.nuiton.topia.persistence.TopiaDAO; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.util.EntityListUpdator; import org.nuiton.topia.persistence.util.TopiaEntityBinder; import org.nuiton.topia.persistence.util.TopiaEntityHelper; +import org.nuiton.topia.persistence.util.TopiaEntityRef; import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -34,6 +50,9 @@ import java.util.Set; */ public class ReferentialServiceImpl extends AbstractObserveService implements ReferentialService { + /** Logger. */ + private static final Log log = LogFactory.getLog(ReferentialServiceImpl.class); + @Override public List<Program> getAllProgramStub() { @@ -78,7 +97,7 @@ public class ReferentialServiceImpl extends AbstractObserveService implements Re return Lists.newArrayList(entities); } - @Override + @Override public <E extends ReferenceEntity> List<E> loadAndDecorateList(Class<E> entityType) { List<E> entities = getDao(entityType).findAll(); @@ -131,6 +150,26 @@ public class ReferentialServiceImpl extends AbstractObserveService implements Re } @Override + public Collection<? extends TopiaEntity> loadSimpleEntities(Collection<String> entityIds) { + + Collection<TopiaEntity> result = new ArrayList<TopiaEntity>(); + + for (String entityId : entityIds) { + + TopiaEntity entityToLoad = getTransaction().findByTopiaId(entityId); + TopiaDAO<TopiaEntity> dao = getDao(entityToLoad); + TopiaEntity entityLoaded = dao.newInstance(); + loadEntity(entityToLoad, entityLoaded); + + result.add(entityLoaded); + + } + + return result; + + } + + @Override public Set<String> getSpeciesListSpeciesIds(String speciesListId) { SpeciesList speciesList = findByTopiaId(SpeciesList.class, speciesListId); @@ -141,6 +180,143 @@ public class ReferentialServiceImpl extends AbstractObserveService implements Re } + /** + * Recherche d'un {@link LengthWeightParameter} à partir des paramètres donnés. + * <p/> + * La recherche peut ne peut être aussi exacte que les paramètres donnés : + * <p/> + * Dans le cas d'une espèce faune, si non trouvé alors on recherche sur son + * speciesGroup d'espèce. + * <p/> + * Si non trouvé pour l'océan donné (et que celui-ci est non null), alors on + * recherche avec un ocean vide. + * <p/> + * Si non trouvé sur le gender (et que le gender n'est pas indéterminé) , alors + * on recherche avec le gender indéterminé (gender=0). + * + * @param species l'espèce sur lequel on recherche le paramétrage + * @param ocean l'ocean recherché (peut être null) + * @param sex le sexe recherché (on essayera sans sexe (sexe.code=0) si non trouvé) + * @param date le jour recherché + * @return le paramétrage adéquate + * @since 1.5 + */ + public LengthWeightParameter findLengthWeightParameter(Species species, Ocean ocean, Sex sex, Date date) throws ObserveTechnicalException { + + LengthWeightParameterDAO dao = (LengthWeightParameterDAO) getDao(LengthWeightParameter.class); + List<LengthWeightParameter> list = dao.findAllBySpecies(species); + + if (CollectionUtils.isEmpty(list)) { + + // aucun parametrage pour le type donne + return null; + + } + + // filtrage par ocean + list = LengthWeightParemeterHelper.filterByOcean(list, ocean); + + if (CollectionUtils.isEmpty(list) && ocean != null) { + + // filtre par ocean null + list = LengthWeightParemeterHelper.filterByOcean(list, null); + + } + + if (CollectionUtils.isEmpty(list)) { + + // pas d'ocean adequate + return null; + + } + + // filtrage par sexe + list = LengthWeightParemeterHelper.filterBySexe(list, sex); + + if (CollectionUtils.isEmpty(list)) { + + // Sex with code 0 + Sex unkwonSex = ((SexDAO) getDao(Sex.class)).getUnknownSex(); + + if (unkwonSex.equals(sex)) { + + // filtrage par sexe indetermine + list = LengthWeightParemeterHelper.filterBySexe(list, unkwonSex); + + } + + + } + + if (CollectionUtils.isEmpty(list)) { + + // pas de sexe adequate + return null; + + } + + // filtrage par startDate de validite + list = LengthWeightParemeterHelper.filterByDateDebutValidite(list, date); + + if (CollectionUtils.isEmpty(list)) { + + // pas de date de debut adequate + return null; + + } + + // filtrage par endDate de validite + list = LengthWeightParemeterHelper.filterByDateFinValidite(list, date); + + if (CollectionUtils.isEmpty(list)) { + + // pas de date de fin adequate + return null; + + } + + // au final il ne devrait en rester qu'un + + if (list.size() > 1) { + + StringBuilder sb = new StringBuilder("Il existe plusieurs paramétrages possibles pour les données suivantes :"); + sb.append("\nEspece : "); + sb.append(decorateEntity(species)); + sb.append("\nOcean : "); + sb.append(decorateEntity(ocean)); + sb.append("\nSex : "); + sb.append(decorateEntity(sex)); + sb.append("\nDate : ").append(date); + sb.append("\nParamétrages trouvés : "); + for (LengthWeightParameter p : list) { + sb.append("\n - ").append(decorateEntity(p)); + } + + //FIXME Use a specific exception for this + throw new ObserveTechnicalException(sb.toString()); + + } + + LengthWeightParameter result = list.get(0); + if (log.isDebugEnabled()) { + + StringBuilder sb = new StringBuilder("Paramétrage trouvé pour les données suivantes :"); + sb.append("\nEspece : "); + sb.append(decorateEntity(species)); + sb.append("\nOcean : "); + sb.append(decorateEntity(ocean)); + sb.append("\nSex : "); + sb.append(decorateEntity(sex)); + sb.append("\nDate : ").append(date); + sb.append("\nParamétrage: ").append(decorateEntity(result)); + log.debug(sb.toString()); + + } + + return result; + + } + @Override public <R extends ReferenceEntity> R preCreate(Class<R> entityType) { @@ -203,6 +379,159 @@ public class ReferentialServiceImpl extends AbstractObserveService implements Re } + + @Override + public void deleteEntities(Collection<String> entityIds) { + + for (String entityId : entityIds) { + + TopiaEntity entityToDelete = getTransaction().findByTopiaId(entityId); + Class<TopiaEntity> entityType = getEntityContractClass(entityToDelete); + TopiaDAO<TopiaEntity> dao = getDao(entityType); + dao.delete(entityToDelete); + + } + } + + @Override + public void copySimpleEntities(Collection<? extends TopiaEntity> entities) { + + for (TopiaEntity entity : entities) { + + TopiaDAO<TopiaEntity> dao = getDao(entity); + + TopiaEntity entityLoaded = dao.findByTopiaId(entity.getTopiaId()); + loadEntity(entity, entityLoaded); + + } + + } + + @Override + public void replaceObsoleteReference(ObsoleteReferenceToReplace action) { + + String obsoleteId = action.getObsoleteId(); + String safeId = action.getSafeId(); + TopiaEntityRef[] refs = action.getRefs(); + + if (log.isInfoEnabled()) { + log.info("load obsolete object " + obsoleteId); + } + + if (log.isInfoEnabled()) { + log.info("load safe object " + safeId); + } + + TopiaEntity safeRef = getTransaction().findByTopiaId(safeId); + + // on remplace les references + for (TopiaEntityRef ref : refs) { + + TopiaEntity invoker = ref.getInvoker(); + + if (invoker == null) { + throw new NullPointerException("can not have a null invoker in " + ref); + } + + TopiaDAO<TopiaEntity> dao = getDao(invoker); + + + if (log.isInfoEnabled()) { + log.info("load invoker object " + invoker.getTopiaId()); + } + + invoker = dao.findByTopiaId(invoker.getTopiaId()); + + // switch entity + + String path = ref.getInvokerProperty(); + + JXPathContext jxcontext = JXPathContext.newContext(invoker); + + TopiaEntity oldValue = (TopiaEntity) jxcontext.getValue(path); + + if (log.isDebugEnabled()) { + log.debug("property to switch " + path + " old : " + + oldValue); + } + + if (log.isInfoEnabled()) { + log.info("change path : " + path); + log.info("old value : " + oldValue.getTopiaId()); + } + + jxcontext.setValue(path, safeRef); + + TopiaEntity newValue = (TopiaEntity) jxcontext.getValue(path); + + if (log.isInfoEnabled()) { + log.info("new value : " + newValue.getTopiaId()); + } + if (log.isDebugEnabled()) { + log.debug("property to switch " + path + " new : " + + safeRef); + log.debug("property to switch " + path + " new Check : " + + newValue); + } + + dao.update(invoker); + + } + + } + + protected <E extends TopiaEntity> void loadEntity(E source, E target) { + + getBinderService().simpleCopy(source, target, false); + + if (source instanceof Species) { + + // Need also to bind ocean + loadAssociation(Species.class, Ocean.class, Species.PROPERTY_OCEAN, (Species) source, (Species) target); + + } else if (source instanceof SpeciesList) { + + // Need also to bind species + loadAssociation(SpeciesList.class, Species.class, SpeciesList.PROPERTY_SPECIES, (SpeciesList) source, (SpeciesList) target); + + } + + } + + public <E extends TopiaEntity, C extends TopiaEntity> void loadAssociation(Class<E> entityType, + Class<C> childEntityType, + String propertyName, + E source, + E target) { + + EntityListUpdator<E, C> listUpdator = EntityListUpdator.newEntityListUpdator(entityType, childEntityType, propertyName); + + int size = listUpdator.size(source); + + List<C> targetList = Lists.newArrayListWithCapacity(size); + + if (size > 0) { + + TopiaDAO<C> dao = getDao(childEntityType); + + Collection<C> sourceList = listUpdator.getChilds(source); + + for (C childToLoad : sourceList) { + + C childLoaded = dao.newInstance(); + childLoaded.setTopiaId(childToLoad.getTopiaId()); + childLoaded.setTopiaVersion(childToLoad.getTopiaVersion()); + childLoaded.setTopiaCreateDate(childToLoad.getTopiaCreateDate()); + targetList.add(childLoaded); + + } + + } + + listUpdator.setChilds(target, targetList); + + } + protected static Map<Class<? extends ReferenceEntity>, String[]> NATURAL_IDS; protected static Map<Class<? extends ReferenceEntity>, String[]> getNaturalIds() { diff --git a/observe-swing/src/main/java/fr/ird/observe/ObserveContext.java b/observe-swing/src/main/java/fr/ird/observe/ObserveContext.java index 750762e..4c88c27 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ObserveContext.java +++ b/observe-swing/src/main/java/fr/ird/observe/ObserveContext.java @@ -429,7 +429,7 @@ public class ObserveContext extends ObserveApplicationContext { DataSource source = event.getSource(); // on désenregistre la source du service de données - getDataService().unregisterDataSource(source); + ObserveServiceHelper.get().setDataSource(null); // on dettache la validation getValidationContext().closeDataSource(); @@ -480,7 +480,7 @@ public class ObserveContext extends ObserveApplicationContext { protected void openOnUI(DataSource source) throws DataSourceException { // on rend le service disponible dans le service de données - getDataService().registerDataSource(source); + ObserveServiceHelper.get().setDataSource(source); // on rend le service disponible dans le service de validation getValidationContext().setDataSource(source); diff --git a/observe-swing/src/main/java/fr/ird/observe/ObserveRunner.java b/observe-swing/src/main/java/fr/ird/observe/ObserveRunner.java index 68a2118..fc1b404 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ObserveRunner.java +++ b/observe-swing/src/main/java/fr/ird/observe/ObserveRunner.java @@ -86,12 +86,12 @@ public abstract class ObserveRunner extends ApplicationRunner { return (ObserveRunner) ApplicationRunner.getRunner(); } - public static ObserveResourceManager getResourceManager() { - if (resourceManager == null) { - throw new IllegalStateException("No resourceManager initialized"); - } - return resourceManager; - } +// public static ObserveResourceManager getResourceManager() { +// if (resourceManager == null) { +// throw new IllegalStateException("No resourceManager initialized"); +// } +// return resourceManager; +// } public static ObserveActionExecutor getActionExecutor() { if (actionExecutor == null) { @@ -254,7 +254,6 @@ public abstract class ObserveRunner extends ApplicationRunner { context, ObserveContext.CONFIG_ENTRY_DEF, ObserveContext.ACTIONS_ENTRY_DEF, - ObserveContext.DATA_SERVICE_ENTRY_DEF, ObserveContext.DECORATOR_SERVICE_ENTRY_DEF ); @@ -602,8 +601,8 @@ public abstract class ObserveRunner extends ApplicationRunner { // add config ObserveContext.CONFIG_ENTRY_DEF.setContextValue(instance, config); - // add dataService - instance.getDataService(); +// // add dataService +// instance.getDataService(); // add data context instance.getDataContext(); diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/ObserveMainUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/ObserveMainUIHandler.java index 2360afa..19db078 100755 --- a/observe-swing/src/main/java/fr/ird/observe/ui/ObserveMainUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/ObserveMainUIHandler.java @@ -21,7 +21,6 @@ */ package fr.ird.observe.ui; -import fr.ird.observe.DataService; import fr.ird.observe.DecoratorService; import fr.ird.observe.ObserveConfig; import fr.ird.observe.ObserveContext; @@ -274,9 +273,9 @@ public class ObserveMainUIHandler { return source; } - protected static DataService getDataService() { - return ObserveContext.get().getDataService(); - } +// protected static DataService getDataService() { +// return ObserveContext.get().getDataService(); +// } public static void restartEdit() { ContentUI<?> selectedUI = ObserveContext.get().getSelectedContentUI(); diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUIHandler.java index e5f1f1f..5195f51 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUIHandler.java @@ -21,34 +21,24 @@ */ package fr.ird.observe.ui.admin; -import fr.ird.observe.BinderService; -import fr.ird.observe.DataService; import fr.ird.observe.DecoratorService; import fr.ird.observe.ObserveContext; -import fr.ird.observe.ObserveDAOHelper; import fr.ird.observe.ObserveRunner; -import fr.ird.observe.ObserveServiceHelper; import fr.ird.observe.SendMessageAble; import fr.ird.observe.db.DataSource; import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.db.ReplicationService; import fr.ird.observe.db.event.DataSourceEvent; import fr.ird.observe.db.event.DataSourceListener; import fr.ird.observe.db.event.DataSourceListenerAdapter; -import fr.ird.observe.services.model.DataSelectionModel; import fr.ird.observe.gps.GPSService; +import fr.ird.observe.services.model.DataSelectionModel; import fr.ird.observe.ui.admin.config.SelectDataUI; import fr.ird.observe.ui.admin.resume.ShowResumeUI; import fr.ird.observe.ui.tree.DataSelectionTreeSelectionModel; import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.validation.ValidationService; import jaxx.runtime.swing.wizard.ext.WizardState; 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 javax.swing.JTree; import javax.swing.tree.TreeModel; @@ -82,8 +72,7 @@ public class AdminTabUIHandler implements SendMessageAble { DataSource service = event.getSource(); if (event.getMessageLevel() == DataSourceEvent.MessageLevel.INFO) { - sendMessage(service.getShortLabel() + " : " + - event.getMessage()); + sendMessage(service.getShortLabel() + " : " + event.getMessage()); } } }; @@ -91,20 +80,6 @@ public class AdminTabUIHandler implements SendMessageAble { protected AdminUI parentUI; /** - * Service de replication. - * <p/> - * Note: le service est sans état et donc peut rester en état du handler. - */ - private ReplicationService replicationService; - - /** - * Service de replication. - * <p/> - * Note: le service est sans état et donc peut rester en état du handler. - */ - private ValidationService validationService; - - /** * Service de gps. * <p/> * Note: le service est sans état et donc peut rester en état du handler. @@ -114,12 +89,6 @@ public class AdminTabUIHandler implements SendMessageAble { /** Service de decoration. */ private DecoratorService decoratorService; - /** Service de manipulation de données depuis des bases. */ - private DataService dataService; - - /** Service de binders. */ - private BinderService binderService; - public AdminTabUIHandler(AdminTabUI ui) { this.ui = ui; model = ui.getModel(); @@ -133,20 +102,6 @@ public class AdminTabUIHandler implements SendMessageAble { return model; } - public final ReplicationService getReplicationService() { - if (replicationService == null) { - replicationService = ObserveServiceHelper.newReplicationService(); - } - return replicationService; - } - - public final ValidationService getValidationService() { - if (validationService == null) { - validationService = ObserveServiceHelper.newValidationService(); - } - return validationService; - } - public final DecoratorService getDecoratorService() { if (decoratorService == null) { decoratorService = ObserveContext.get().getDecoratorService(); @@ -154,20 +109,6 @@ public class AdminTabUIHandler implements SendMessageAble { return decoratorService; } - public final DataService getDataService() { - if (dataService == null) { - dataService = ObserveContext.get().getDataService(); - } - return dataService; - } - - public final BinderService getBinderService() { - if (binderService == null) { - binderService = ObserveContext.get().getBinderService(); - } - return binderService; - } - public final GPSService getGpsService() { if (gpsService == null) { gpsService = ObserveContext.get().getGPSService(); @@ -182,67 +123,28 @@ public class AdminTabUIHandler implements SendMessageAble { source = model.getSafeLocalSource(false); } return source; + } public final WizardState onCancel(Exception e) { + if (log.isDebugEnabled()) { log.debug(this, e); } sendMessage(t("observe.message.synchro.operation.canceled")); return WizardState.CANCELED; + } public final WizardState onError(Exception e) { + model.getStepModel(model.getOperation()).setError(e); if (log.isErrorEnabled()) { log.error(e.getMessage(), e); } sendMessage(t("observe.message.synchro.operation.failed")); return WizardState.FAILED; - } - - protected void replicateData(DataSource source, - DataSource target, - String... tripIds) throws DataSourceException { - ReplicationService service = getReplicationService(); - if (tripIds == null || tripIds.length == 0) { - - // on replique toutes les données - service.replicateAllData(source, target); - } else { - - // on replique les données specifiees - service.replicateData(source, target, tripIds); - } - } - - protected void replicateReferentiel(DataSource source, - DataSource target) throws DataSourceException { - getReplicationService().replicateReferentiel(source, target); - } - - protected TopiaContext beginTransaction(DataSource source, String methodName) throws DataSourceException { - TopiaContext ctxt = source.beginTransaction(methodName); - return ctxt; - } - - protected void commitTransaction(DataSource source, TopiaContext tx, String methodName) throws DataSourceException { - source.commitTransaction(tx, methodName); - } - - protected void closeTransaction(DataSource source, TopiaContext tx, String methodName) throws DataSourceException { - source.closeTransaction(tx, methodName); - } - - protected void rollbackTransaction(DataSource source, TopiaContext tx, String methodName) throws DataSourceException { - source.rollbackTransaction(tx, methodName); - } - - protected TopiaDAO<TopiaEntity> getDAO(TopiaContext tx, TopiaEntity entity) throws TopiaException { - TopiaDAO<TopiaEntity> dao = - ObserveDAOHelper.<TopiaEntity, TopiaDAO<TopiaEntity>>getDAO(tx, entity); - return dao; } public void initTabUI(AdminUI ui, AdminTabUI tabUI) { @@ -267,6 +169,7 @@ public class AdminTabUIHandler implements SendMessageAble { } public void updateState(AdminTabUI ui, WizardState newState) { + if (newState == null) { newState = WizardState.PENDING; } @@ -298,6 +201,7 @@ public class AdminTabUIHandler implements SendMessageAble { ui.CANCELED_progressionPane.setColumnHeaderView(ui.progressionTop); break; } + } public void sendMessage(String msg) { diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIModel.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIModel.java index 823288e..92a6411 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIModel.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIModel.java @@ -21,10 +21,10 @@ */ package fr.ird.observe.ui.admin; -import fr.ird.observe.DataService; import fr.ird.observe.ObserveConfig; import fr.ird.observe.ObserveContext; import fr.ird.observe.ObserveServiceHelper; +import fr.ird.observe.db.DataContext; import fr.ird.observe.db.DataSource; import fr.ird.observe.db.DataSourceConfig; import fr.ird.observe.db.DataSourceException; @@ -76,10 +76,6 @@ import static org.nuiton.i18n.I18n.t; */ public class AdminUIModel extends WizardExtModel<AdminStep> { - public static final String SHOW_RESUME_PROPERTY_NAME = "showResume"; - - public static final String NEED_LOCAL_SOURCE_PROPERTY_NAME = "needLocalSource"; - public static final String SELECTION_MODEL_CHANGED_PROPERTY_NAME = "selectionModelChanged"; public static final String SELECTED_TRIP_PROPERTY_NAME = "selectedTrip"; @@ -108,12 +104,11 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { /** le controleur pour configurer les sources */ protected StorageUIHandler storageHandler; - /** data service pour effectuer des opérations sur les sources */ - protected DataService dataService; - /** configuration de l'application */ protected ObserveConfig config; + private DataContext dataContext; + /** selection des donnees a valider */ protected DataSelectionModel selectionDataModel; @@ -121,6 +116,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { protected EnumSet<DbMode> availableIncomingModes; PropertyChangeListener listenStepChanged = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { @@ -229,6 +225,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { }; PropertyChangeListener listenValidationModified = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { ValidateModel source = (ValidateModel) evt.getSource(); @@ -248,6 +245,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { }; PropertyChangeListener listenReportModified = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { ReportModel source = (ReportModel) evt.getSource(); @@ -262,6 +260,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { }; PropertyChangeListener listenerSelectedDataForReport = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { @@ -275,6 +274,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { }; PropertyChangeListener listenConsolidateModified = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { ConsolidateModel source = (ConsolidateModel) evt.getSource(); @@ -289,6 +289,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { }; PropertyChangeListener listenGPSModified = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { if (log.isDebugEnabled()) { @@ -301,6 +302,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { }; PropertyChangeListener listenSaveLocalChanged = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { @@ -447,14 +449,14 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { return (AdminActionModel) super.getStepModel(operation); } - public DataService getDataService() { - return dataService; - } - public ObserveConfig getConfig() { return config; } + public DataContext getDataContext() { + return dataContext; + } + /** * Pour savoir si on a besoin d'une base source pour l'opération. * <p/> @@ -520,8 +522,9 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { availableIncomingModes.clear(); storageHandler = ui.getContextValue(StorageUIHandler.class); - dataService = ui.getContextValue(DataService.class); +// dataService = ui.getContextValue(DataService.class); config = ui.getContextValue(ObserveConfig.class); + dataContext = ui.getContextValue(DataContext.class); // demarrage du modèle : on fixe ici une fois pour toute les liste // des onglets visibles @@ -659,6 +662,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { if (log.isDebugEnabled()) { centralSourceModel.addPropertyChangeListener(new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); @@ -758,6 +762,7 @@ public class AdminUIModel extends WizardExtModel<AdminStep> { if (log.isDebugEnabled()) { localSourceModel.addPropertyChangeListener(new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateModel.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateModel.java index ed72580..7f35319 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateModel.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateModel.java @@ -21,14 +21,12 @@ */ package fr.ird.observe.ui.admin.consolidate; +import com.google.common.base.Preconditions; +import fr.ird.observe.ObserveContext; import fr.ird.observe.db.DataSource; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TripSeine; +import fr.ird.observe.services.ObserveServiceFactory; import fr.ird.observe.ui.admin.AdminActionModel; import fr.ird.observe.ui.admin.AdminStep; -import org.nuiton.decorator.Decorator; /** * Modele pour preparer une validation de donnees d'une base. @@ -41,13 +39,7 @@ public class ConsolidateModel extends AdminActionModel { /** la source de données où effectuer la consolidation des données */ private DataSource source; - private Decorator<Program> programDecorator; - - private Decorator<TripSeine> tripDecorator; - - private Decorator<SetSeine> setDecorator; - - private Decorator<ActivitySeine> activityDecorator; + protected ObserveServiceFactory serviceFactory; public ConsolidateModel() { super(AdminStep.CONSOLIDATE); @@ -59,43 +51,28 @@ public class ConsolidateModel extends AdminActionModel { public void setSource(DataSource source) { this.source = source; + if (serviceFactory != null) { + serviceFactory.close(); + serviceFactory = null; + } } - public Decorator<Program> getProgramDecorator() { - return programDecorator; - } - - public void setProgramDecorator(Decorator<Program> programDecorator) { - this.programDecorator = programDecorator; - } - - public Decorator<TripSeine> getTripDecorator() { - return tripDecorator; - } + public ObserveServiceFactory getServiceFactory() { - public void setTripDecorator(Decorator<TripSeine> tripDecorator) { - this.tripDecorator = tripDecorator; - } + if (serviceFactory == null) { - public Decorator<SetSeine> getSetDecorator() { - return setDecorator; - } + Preconditions.checkNotNull(source, "Can't create source service factory if source is null"); + serviceFactory = ObserveContext.newServiceFactory(source); - public void setSetDecorator(Decorator<SetSeine> setDecorator) { - this.setDecorator = setDecorator; - } + } + return serviceFactory; - public Decorator<ActivitySeine> getActivityDecorator() { - return activityDecorator; - } - - public void setActivityDecorator(Decorator<ActivitySeine> activityDecorator) { - this.activityDecorator = activityDecorator; } @Override public void destroy() { super.destroy(); - source = null; + setSource(null); } + } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUIHandler.java index be55ccb..d5da3d8 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUIHandler.java @@ -21,17 +21,10 @@ */ package fr.ird.observe.ui.admin.consolidate; -import fr.ird.observe.ConsolidateDataService; -import fr.ird.observe.DecoratorService; -import fr.ird.observe.ObserveServiceHelper; import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; +import fr.ird.observe.services.ObserveServiceFactory; import fr.ird.observe.services.model.DataSelectionModel; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TripSeine; +import fr.ird.observe.services.operation.ComputeDataService; import fr.ird.observe.ui.admin.AdminStep; import fr.ird.observe.ui.admin.AdminTabUI; import fr.ird.observe.ui.admin.AdminTabUIHandler; @@ -41,15 +34,11 @@ import fr.ird.observe.ui.admin.config.SelectDataUI; import jaxx.runtime.swing.wizard.ext.WizardState; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.persistence.TopiaDAO; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; -import java.util.ArrayList; import java.util.Date; -import java.util.List; +import java.util.Set; import java.util.concurrent.Callable; import static org.nuiton.i18n.I18n.t; @@ -83,32 +72,31 @@ public class ConsolidateUIHandler extends AdminTabUIHandler { System.identityHashCode(ui)); } - tabUI.getStartButton().setText( - t("observe.action.synchro.launch.operation", - t(tabUI.getStep().getOperationLabel()))); + tabUI.getStartButton().setText(t("observe.action.synchro.launch.operation", t(tabUI.getStep().getOperationLabel()))); - final SelectDataUI selectTabUI = (SelectDataUI) - ui.getStepUI(AdminStep.SELECT_DATA); + final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); PropertyChangeListener listener = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { - AdminUIModel model = (AdminUIModel) evt.getSource(); - if (!model.containsStep(selectTabUI.getStep())) { - // avoid multi-cast - return; - } - DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug("selection model changed to " + value); + + AdminUIModel source = (AdminUIModel) evt.getSource(); + if (source.containsStep(selectTabUI.getStep())) { + + DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); + if (log.isDebugEnabled()) { + log.debug("selection model changed to " + value); + } + updateSelectionModel(selectTabUI); + } - updateSelectionModel(selectTabUI); + } }; - tabUI.getModel().addPropertyChangeListener( - AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, - listener - ); + + tabUI.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, listener); + } public void startAction() { @@ -116,12 +104,14 @@ public class ConsolidateUIHandler extends AdminTabUIHandler { addAdminWorker( ((ConsolidateUI) ui).getStartButton().getToolTipText(), new Callable<WizardState>() { + @Override public WizardState call() throws Exception { return doAction(); } } ); + } public WizardState doAction() throws Exception { @@ -136,72 +126,27 @@ public class ConsolidateUIHandler extends AdminTabUIHandler { // une erreur ou une annulation return init; } - java.util.Set<String> tripIds = model.getSelectionDataModel().getSelectedData(); - List<TripSeine> toUpdate = new ArrayList<TripSeine>(tripIds.size()); - - ConsolidateDataService service = - ObserveServiceHelper.getConsolidateDataService(); - - DataSource source = getStepModel().getSource(); - String txName = "consolidateData"; - - TopiaContext tx = source.beginTransaction(txName); - try { - TopiaDAO<TripSeine> dao = source.getDAO(tx, TripSeine.class); - for (String mareeId : tripIds) { - if (Entities.isSeineId(mareeId)) { + Set<String> tripIds = model.getSelectionDataModel().getSelectedData(); - TripSeine trip = (TripSeine) tx.findByTopiaId(mareeId); + ObserveServiceFactory serviceFactory = getStepModel().getServiceFactory(); - boolean needUpdate = service.consolidateTrip(this, tx, trip); - if (needUpdate) { + ComputeDataService service = serviceFactory.getService(ComputeDataService.class); - // on met a jour la maree en base - dao.update(trip); - - // on conserve une reference sur la maree mise à jour - toUpdate.add(trip); - } - - } - - } - - // on commite si quelque chose a ete mise a jour - boolean needCommit = !toUpdate.isEmpty(); - - if (needCommit) { - - sendMessage(t("observe.message.consolidate.save.changes", - toUpdate.size())); - source.commitTransaction(tx, txName); - } + try { - } catch (Exception eee) { - try { - source.rollbackTransaction(tx, txName); - } catch (DataSourceException e1) { + service.consolidateTrips(this, tripIds); - // une autre erreur lors du rollback, qui ne doit pas empecher - // de continuer le traitement - if (log.isErrorEnabled()) { - log.error(e1); - } - } - throw eee; } finally { - // clean service - service.clear(); + service.close(); - // toujours fermer la transaction - source.closeTransaction(tx, txName); } - sendMessage(t("observe.message.consolidate.operation.done", - new Date())); + sendMessage(t("observe.message.consolidate.operation.done", new Date())); + return WizardState.SUCCESSED; + } @@ -213,18 +158,6 @@ public class ConsolidateUIHandler extends AdminTabUIHandler { openSource(source); - DecoratorService dProvider = getDecoratorService(); - ConsolidateModel stepModel = getStepModel(); - - Decorator<Program> p = dProvider.getDecoratorByType(Program.class); - Decorator<TripSeine> m = dProvider.getDecoratorByType(TripSeine.class); - Decorator<ActivitySeine> a = dProvider.getDecoratorByType(ActivitySeine.class); - Decorator<SetSeine> c = dProvider.getDecoratorByType(SetSeine.class); - stepModel.setProgramDecorator(p); - stepModel.setTripDecorator(m); - stepModel.setActivityDecorator(a); - stepModel.setSetDecorator(c); - return null; } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportModel.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportModel.java index 29ee79a..8233e85 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportModel.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportModel.java @@ -21,8 +21,11 @@ */ package fr.ird.observe.ui.admin.export; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import fr.ird.observe.ObserveContext; import fr.ird.observe.db.DataSource; +import fr.ird.observe.services.ObserveServiceFactory; import fr.ird.observe.services.model.DataSelectionModel; import fr.ird.observe.entities.Trip; import fr.ird.observe.entities.longline.TripLongline; @@ -64,6 +67,8 @@ public class ExportModel extends AdminActionModel { protected DataSource centralSource; + protected ObserveServiceFactory centralServiceFactory; + public ExportModel() { super(AdminStep.EXPORT_DATA); } @@ -140,6 +145,20 @@ public class ExportModel extends AdminActionModel { public void setCentralSource(DataSource centralSource) { this.centralSource = centralSource; + if (centralServiceFactory != null) { + centralServiceFactory.close(); + centralServiceFactory = null; + } + } + + public ObserveServiceFactory getCentraServiceFactory() { + + if (centralServiceFactory == null) { + Preconditions.checkNotNull(centralSource, "Can't create source service factory if centralSource is null"); + centralServiceFactory = ObserveContext.newServiceFactory(centralSource); + } + return centralServiceFactory; + } public void setProgramDecorator(Decorator<Program> programDecorator) { diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUIHandler.java index c47c714..12e9561 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUIHandler.java @@ -22,13 +22,13 @@ package fr.ird.observe.ui.admin.export; import fr.ird.observe.DecoratorService; -import fr.ird.observe.ObserveContext; import fr.ird.observe.db.DataSource; import fr.ird.observe.entities.Trip; import fr.ird.observe.entities.longline.TripLongline; import fr.ird.observe.entities.referentiel.Program; import fr.ird.observe.entities.seine.TripSeine; import fr.ird.observe.services.ObserveServiceFactory; +import fr.ird.observe.services.ReplicationService; import fr.ird.observe.services.data.TripService; import fr.ird.observe.services.model.DataSelectionModel; import fr.ird.observe.ui.UIHelper; @@ -86,6 +86,7 @@ public class ExportUIHandler extends AdminTabUIHandler { final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); tabUI.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { AdminUIModel model = (AdminUIModel) evt.getSource(); @@ -166,6 +167,7 @@ public class ExportUIHandler extends AdminTabUIHandler { addAdminWorker( ((ExportUI) ui).getPrepareAction().getToolTipText(), new Callable<WizardState>() { + @Override public WizardState call() throws Exception { return prepareAction(); @@ -184,6 +186,7 @@ public class ExportUIHandler extends AdminTabUIHandler { addAdminWorker( tabUI.getStartAction().getToolTipText(), new Callable<WizardState>() { + @Override public WizardState call() throws Exception { return doAction(); @@ -236,45 +239,44 @@ public class ExportUIHandler extends AdminTabUIHandler { List<TripEntry> entries = stepModel.getData(); if (entries.isEmpty()) { + // pas de données possible à exporter sendMessage(t("observe.message.exportData.not.possible")); sendMessage(t("observe.message.synchro.operation.done", new Date())); return WizardState.CANCELED; + } sendMessage(t("observe.message.exportData.operation.needFix", new Date())); // on rend la main à l'ui pour que l'utilisateur selectionne les marees a exporter return WizardState.NEED_FIX; + } public WizardState doAction() throws Exception { ExportModel stepModel = model.getExportModel(); - DataSource centralSource = stepModel.getCentralSource(); - DataSource localSource = stepModel.getSource(); - - ObserveServiceFactory centralServices = ObserveContext.newServiceFactory(centralSource); - ObserveServiceFactory localServices = ObserveContext.newServiceFactory(localSource ); - // on filtre les marées sélectionnées pour export List<TripEntry> tripEntries = stepModel.getSelectedTrips(); for (TripEntry tripEntry : tripEntries) { - processTrip(stepModel, tripEntry,localServices, centralServices); + processTrip(stepModel, tripEntry); } sendMessage(t("observe.message.synchro.operation.done", new Date())); return WizardState.SUCCESSED; + } - protected void processTrip(ExportModel stepModel, TripEntry tripEntry, ObserveServiceFactory localServices, ObserveServiceFactory centralServices) throws Exception { + protected void processTrip(ExportModel stepModel, TripEntry tripEntry) throws Exception { + + ObserveServiceFactory centralServices = stepModel.getCentraServiceFactory(); - DataSource centralSource = stepModel.getCentralSource(); DataSource source = stepModel.getSource(); Trip trip = tripEntry.getTrip(); @@ -303,26 +305,8 @@ public class ExportUIHandler extends AdminTabUIHandler { } sendMessage(t("observe.message.exportData.replicate.maree", tripDecorated, programDecorated)); - try { - replicateData(source, centralSource, tripId); - } catch (Exception e) { - //FIXME 20100726 : il faut supprimer tous les objets crées pour cette marée - -// tx = beginTransaction(centralSource, txName); -// -// // on supprime la maree qui n'a pas pu etre importee -// try { -// TopiaDAO<Trip> dao = ObserveDAOHelper.getTripSeineDAO(tx); -// // on recharge la données depuis la base centrale -// m = dao.findByTopiaId(m.getTopiaId()); -// dao.delete(m); -// commitTransaction(centralSource, tx, txName); -// } finally { -// closeTransaction(centralSource, tx, txName); -// } - - throw e; - } + ReplicationService service = centralServices.getService(ReplicationService.class); + service.replicateData(source, tripId); } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/gps/ImportGPSUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/gps/ImportGPSUIHandler.java index b440c9c..516ad80 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/gps/ImportGPSUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/gps/ImportGPSUIHandler.java @@ -22,14 +22,15 @@ package fr.ird.observe.ui.admin.gps; import fr.ird.observe.DecoratorService; +import fr.ird.observe.ObserveContext; import fr.ird.observe.db.DataSource; -import fr.ird.observe.entities.OpenableEntities; import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.Route; import fr.ird.observe.entities.seine.TripSeine; import fr.ird.observe.gps.GPSPoint; import fr.ird.observe.gps.GPSPointInterval; import fr.ird.observe.gps.GPSRoute; +import fr.ird.observe.services.ObserveServiceFactory; +import fr.ird.observe.services.operation.GpsImportService; import fr.ird.observe.ui.UIHelper; import fr.ird.observe.ui.admin.AdminStep; import fr.ird.observe.ui.admin.AdminTabUIHandler; @@ -39,15 +40,9 @@ import jaxx.runtime.context.JAXXInitialContext; import jaxx.runtime.swing.editor.MyDefaultCellEditor; import jaxx.runtime.swing.renderer.BooleanCellRenderer; import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.collections.primitives.ArrayIntList; -import org.apache.commons.collections.primitives.IntIterator; -import org.apache.commons.collections.primitives.IntList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.persistence.TopiaDAO; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListSelectionModel; @@ -81,10 +76,6 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { /** Logger */ private static final Log log = LogFactory.getLog(ImportGPSUIHandler.class); - - /** un drapeau pour savoir si on a deja initialise l'action */ - protected boolean wasInit; - /** la route ouverte */ protected TripSeine openTripSeine; @@ -140,6 +131,7 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { configUI.getExtraConfig().add(extraConfig); DefaultListCellRenderer listRenderer = new DefaultListCellRenderer() { + private static final long serialVersionUID = 1L; @Override @@ -181,6 +173,7 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { tabUI.setContextValue(renderer2, "defaultTableRenderer"); DefaultTableCellRenderer renderer3 = new DefaultTableCellRenderer() { + private static final long serialVersionUID = 1L; @Override @@ -254,6 +247,7 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { n("observe.synchro.table.importGPS.computed.label"), n("observe.synchro.table.importGPS.computed.label.tip")); DefaultTableCellRenderer renderer4 = new DefaultTableCellRenderer() { + private static final long serialVersionUID = 1L; @Override @@ -338,6 +332,7 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { addAdminWorker( getUi().getPrepareAction().getToolTipText(), new Callable<WizardState>() { + @Override public WizardState call() throws Exception { return prepareAction(); @@ -356,6 +351,7 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { addAdminWorker( tabUI.getStartAction().getToolTipText(), new Callable<WizardState>() { + @Override public WizardState call() throws Exception { return doAction(); @@ -378,38 +374,37 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { // ouverture de la base locale openSource(source); + ObserveServiceFactory serviceFactory = ObserveContext.newServiceFactory(source); + + GpsImportService service = serviceFactory.getService(GpsImportService.class); + // récuperation de la marée ouverte - TopiaContext srcCtxt = beginTransaction(source, "beforeAction"); - try { - openTripSeine = OpenableEntities.getOpenTrip(srcCtxt); - } catch (TopiaException e) { - closeTransaction(source, srcCtxt, "beforeAction"); - } + openTripSeine = service.getOpenTrip(); if (openTripSeine == null) { - // pas de route ouverte + + // pas de marée ouverte sendMessage(t("observe.message.no.open.maree.detected")); return WizardState.FAILED; + } - if (openTripSeine.isRouteEmpty()) { + data = service.getActivitiesForOpenRoute(openTripSeine.getTopiaId()); + + if (data == null) { + // pas de route sur la maree ouverte sendMessage(t("observe.message.no.route.detected")); return WizardState.FAILED; - } - for (Route r : openTripSeine.getRoute()) { - if (!r.isActivitySeineEmpty()) { - // on enregistre les actitives - for (ActivitySeine a : r.getActivitySeine()) { - data.put(a, null); - } - } + } if (data.isEmpty()) { - // pas d'activity a traiter + + // pas d'activité a traiter sendMessage(t("observe.message.no.activity.detected")); return WizardState.FAILED; + } ImportGPSModel gpsModel = model.getImportGPSModel(); @@ -427,9 +422,11 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { List<GPSPointInterval> acceptedInterval = route.getAcceptedInterval(); if (acceptedInterval == null || acceptedInterval.isEmpty()) { + // pas d'intervalle acceptable sendMessage(t("observe.message.no.accepted.intervalle.detected")); return WizardState.FAILED; + } for (GPSPointInterval i : acceptedInterval) { @@ -440,23 +437,24 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { sendMessage(t("observe.message.detected.rejected.interval", i)); } - - // il s'agit de la première passe : detection des point gps - //des activitys + // il s'agit de la première passe : detection des point gps des activités sendMessage(t("observe.message.importGPS.detect.points")); detectPoints(); if (data.isEmpty()) { - // aucune activity modifiable + + // aucune activité modifiable sendMessage(t("observe.message.importGPS.nothing.to.do")); sendMessage(t("observe.message.synchro.operation.done", new Date())); return WizardState.SUCCESSED; + } sendMessage(t("observe.message.importGPS.operation.needFix", new Date())); return WizardState.NEED_FIX; + } public WizardState doAction() throws Exception { @@ -483,6 +481,7 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { sendMessage(t("observe.message.synchro.operation.done", new Date())); return WizardState.SUCCESSED; + } @@ -516,76 +515,21 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { for (ActivitySeine a : rejected) { data.remove(a); } + } protected void applyPoints() throws Exception { int[] selectedIndex = model.getImportGPSModel().getImportGPSSelectedIndex(); - IntList lIndex = new ArrayIntList(selectedIndex.length); - - String txName = "applyPoints"; - TopiaContext ctxt = beginTransaction(source, txName); - - try { + ObserveServiceFactory serviceFactory = ObserveContext.newServiceFactory(source); + GpsImportService service = serviceFactory.getService(GpsImportService.class); + service.applyPoints(data, selectedIndex, this); - for (int i : selectedIndex) { - lIndex.add(i); - } - IntIterator indexItr = lIndex.iterator(); - - int currentActivityIndex = 0; - int nextActivityIndex = indexItr.next(); - - TopiaDAO<ActivitySeine> activityDAO = source.getDAO(ctxt, ActivitySeine.class); - for (ActivitySeine a : data.keySet()) { - if (currentActivityIndex == nextActivityIndex) { - // l'activity courante a ete selectionne - GPSPoint p = data.get(a); - - sendMessage(t("observe.message.importGPS.apply.point", dGPSPoint.toString(p), dActivity.toString(a))); -// sendMessage(t("observe.message.importGPS.apply.point", p, a.getVesselActivity().getLabel2())); - float latitude = Math.abs(p.getLatitude()); - float longitude = Math.abs(p.getLongitude()); - int quadrant = p.getQuadrant(); - // application de la position - - ActivitySeine aa = activityDAO.findByTopiaId(a.getTopiaId()); - aa.setLatitude(latitude); - aa.setLongitude(longitude); - aa.setQuadrant(quadrant); - //TODO appliquer la vitesse ? - //a.setVesselSpeed(p.getVitesse()); - - // mise a jour de l'activity - - activityDAO.update(aa); -// a.update(); - - if (indexItr.hasNext()) { - // il reste au moins une activity a traiter - // recuperation du prochain index d'activity a traiter - nextActivityIndex = indexItr.next(); - } else { - // plus d'activity a traiter - break; - } - } - currentActivityIndex++; - } - - commitTransaction(source, ctxt, txName); - } catch (Exception e) { - rollbackTransaction(source, ctxt, txName); - throw e; - } finally { - - closeTransaction(source, ctxt, txName); - lIndex.clear(); - } } public void chooseImportGPSFile() { + ImportGPSModel gpsModel = getModel().getImportGPSModel(); File f = UIHelper.chooseFile( ui, @@ -595,6 +539,7 @@ public class ImportGPSUIHandler extends AdminTabUIHandler { "^.+\\.gpx$", t("observe.action.choose.importGPS.description")); gpsModel.setImportGPSFile(f); + } } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUIHandler.java index 699e5b1..3951628 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUIHandler.java @@ -21,38 +21,22 @@ */ package fr.ird.observe.ui.admin.save; -import fr.ird.observe.ObserveDAOHelper; +import fr.ird.observe.ObserveContext; import fr.ird.observe.db.DataSource; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.referentiel.Ocean; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.referentiel.SpeciesList; +import fr.ird.observe.services.ObserveServiceFactory; +import fr.ird.observe.services.operation.SynchronizeService; import fr.ird.observe.ui.UIHelper; import fr.ird.observe.ui.admin.AdminStep; import fr.ird.observe.ui.admin.AdminTabUIHandler; import fr.ird.observe.ui.admin.AdminUI; import fr.ird.observe.ui.admin.synchronize.SynchronizeModel; -import fr.ird.observe.ui.admin.synchronize.SynchronizeUIHandler; import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.hibernate.jdbc.Work; -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.util.DiffState; import java.io.File; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; import java.util.Date; -import java.util.List; -import java.util.Map; import java.util.concurrent.Callable; import static org.nuiton.i18n.I18n.t; @@ -68,9 +52,6 @@ public class SaveLocalUIHandler extends AdminTabUIHandler { /** Logger */ private static final Log log = LogFactory.getLog(SaveLocalUIHandler.class); - private static final String UPDATE_VERSION_PATTERN = - "UPDATE %1$s SET topiaversion = %2$d WHERE topiaid='%3$s';\n"; - protected DataSource source; public SaveLocalUIHandler(SaveLocalUI ui) { @@ -115,7 +96,7 @@ public class SaveLocalUIHandler extends AdminTabUIHandler { public void skipOperation() { sendMessage(t("observe.synchro.message.saveLocal.skip")); getModel().setStepState(AdminStep.SAVE_LOCAL, WizardState.SUCCESSED); -// getUi().getProgression().setText(t("observe.synchro.message.saveLocal.skip")); + // on passe directement à l'opération suivante if (model.getNextStep() != null) { model.gotoNextStep(); @@ -145,6 +126,7 @@ public class SaveLocalUIHandler extends AdminTabUIHandler { addAdminWorker( getUi().getStartAction().getToolTipText(), new Callable<WizardState>() { + @Override public WizardState call() throws Exception { return doAction(); @@ -192,8 +174,6 @@ public class SaveLocalUIHandler extends AdminTabUIHandler { public void saveReferentiel() throws Exception { - List<String> ids; - SynchronizeModel stepModel = getModel().getSynchronizeReferentielModel(); DataSource referentielSource = stepModel.getTmpSource(); @@ -202,190 +182,26 @@ public class SaveLocalUIHandler extends AdminTabUIHandler { // pas de base temporaire // on travaille directement sur la base central referentielSource = stepModel.getCentralSource(); - } - DataSource targetSource = stepModel.getSource(); - DiffState.DiffStateMap diff = stepModel.getDiff(); + } - String txName = "saveReferentiel"; - TopiaContext targetTx = beginTransaction(targetSource, txName); + ObserveServiceFactory serviceFactory = ObserveContext.newServiceFactory(referentielSource); try { - TopiaContext sourceTx = beginTransaction(referentielSource, txName); - try { - // ajout des nouvelles entites du referentiel - - ids = diff.get(DiffState.NEW); - if (CollectionUtils.isNotEmpty(ids)) { - for (String id : ids) { - //FIXME on doit s'assurer de l'orde d'injection des entites - TopiaEntity entity = sourceTx.findByTopiaId(id); - String message = t("observe.synchro.add.object", id); - sendMessage(message); - sourceTx.replicateEntity(targetTx, entity); - - // On est obligé de commiter à chaque ajout sinon si - // une autre entité à ajouter depend de celle là, on - // ne la retrouve pas - // - commitTransaction(targetSource, targetTx, txName); - if (log.isDebugEnabled()) { - log.debug("add [" + id + "] : " + targetTx.findByTopiaId(id)); - } - } - } - - // mis a jour des entites modifiees - ids = diff.get(DiffState.MODIFIED); - if (CollectionUtils.isNotEmpty(ids)) { + SynchronizeService service = serviceFactory.getService(SynchronizeService.class); - for (String id : ids) { + DataSource targetSource = stepModel.getSource(); - copyEntity(stepModel, sourceTx, targetTx, id); - } - } + DiffState.DiffStateMap diff = stepModel.getDiff(); - // mise à jour des données utilisateurs (remplacements d'objets obsolètes) + service.saveReferentiel(targetSource, diff, stepModel.getReplaceActions(), this); - for (SynchronizeUIHandler.ObsoleteRefReplaceAction action : stepModel.getReplaceActions()) { - - String message = t("observe.synchro.replaceObsolete.object", action.getObsoleteId()); - sendMessage(message); - - action.doAction(targetTx); - } - - // si on ne commite pas ici, les modifications utilisateurs - // sont perdues - commitTransaction(targetSource, targetTx, txName); - - // suppression des entités obsoletes de la base source - - ids = diff.get(DiffState.REMOVED); - if (CollectionUtils.isNotEmpty(ids)) { - for (String id : ids) { - String message = t("observe.synchro.remove.object", id); - sendMessage(message); - TopiaEntity entity = targetTx.findByTopiaId(id); - getDAO(targetTx, entity).delete(entity); - } - } - - Map<TopiaEntity, Long> versionsToUpdate = - stepModel.getVersionsToUpdate(); - - if (MapUtils.isNotEmpty(versionsToUpdate)) { - - // on applique le patch sur les versions pour bien avoir - // la bonne version de topiaversion et pas seulement un incrément - // de 1 puisque ce champs est géré par hibernate et qu'il ne nous laisse - // pas la possibilité de choisir la valeur qu'on veut attribuer au champs... - patchTopiaVersions((TopiaContextImplementor) targetTx, versionsToUpdate); - } - - commitTransaction(targetSource, targetTx, txName); - } finally { - try { - rollbackTransaction(referentielSource, sourceTx, txName); - } finally { - closeTransaction(referentielSource, sourceTx, txName); - } - } - } catch (Exception e) { - rollbackTransaction(targetSource, targetTx, txName); - throw e; } finally { - closeTransaction(targetSource, targetTx, txName); - } - } - protected <E extends TopiaEntity> void copyEntity(SynchronizeModel synchronizeModel, - TopiaContext sourceTx, - TopiaContext targetTx, - String id) throws TopiaException { - - E source = (E) sourceTx.findByTopiaId(id); - - long sourceVersion = source.getTopiaVersion(); - - String message = t("observe.synchro.update.object", source.getTopiaId(), sourceVersion); - sendMessage(message); - - TopiaDAO<E> dao = ObserveDAOHelper.<E, TopiaDAO<E>>getDAO(targetTx, source); - - E target = dao.findByTopiaId(source.getTopiaId()); - - long targetVersion = target.getTopiaVersion(); - - // bind new entity to old one - copyEntity(targetTx, source, target); - - if (targetVersion < sourceVersion) { - //FIXME chemit : si la version n'est pas exactement celle voulue, - // on positionner à la main la version( hibernate ne nous permet - // pas de le faire - if (log.isDebugEnabled()) { - message = "register [" + source.getTopiaId() + - "] to update version " + sourceVersion + - " to " + targetVersion; - log.debug(message); - } - synchronizeModel.getVersionsToUpdate().put(target, sourceVersion); - } - - // wants to have exactly the same topiaversion after commit - target.setTopiaVersion(source.getTopiaVersion() - 1); - - dao.update(target); - } - - protected <E extends TopiaEntity> void copyEntity(TopiaContext targetTx, E source, E target) throws TopiaException { - - getBinderService().simpleCopy(source, target, false); - - if (source instanceof Species) { - - // Need also to bind ocean - getDataService().copyAssociation(Species.class, Ocean.class, Species.PROPERTY_OCEAN, (Species) source, (Species) target, targetTx); - - } else if (source instanceof SpeciesList) { - - // Need also to bind species - getDataService().copyAssociation(SpeciesList.class, Species.class, SpeciesList.PROPERTY_SPECIES, (SpeciesList) source, (SpeciesList) target, targetTx); + serviceFactory.close(); } } - protected void patchTopiaVersions(TopiaContextImplementor sourceCtxt, - Map<TopiaEntity, Long> versionsToUpdate) throws TopiaException { - - final StringBuilder buffer = new StringBuilder(); - - for (Map.Entry<TopiaEntity, Long> entry : - versionsToUpdate.entrySet()) { - TopiaEntity entity = entry.getKey(); - String id = entity.getTopiaId(); - Long version = entry.getValue(); - String tableName = Entities.getTableName(entity); - buffer.append(String.format(UPDATE_VERSION_PATTERN, tableName, version, id)); - - } - sourceCtxt.getHibernate().doWork(new Work() { - @Override - public void execute(Connection connection) throws SQLException { - String sql = buffer.toString(); - PreparedStatement sta = connection.prepareStatement(sql); - try { - if (log.isDebugEnabled()) { - log.debug("Will execute sql code :\n" + sql); - } - sta.executeUpdate(); - } finally { - sta.close(); - } - } - }); - } - } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/SynchronizeModel.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/SynchronizeModel.java index 9360bde..2e1a8bf 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/SynchronizeModel.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/SynchronizeModel.java @@ -21,7 +21,11 @@ */ package fr.ird.observe.ui.admin.synchronize; +import com.google.common.base.Preconditions; +import fr.ird.observe.ObserveContext; import fr.ird.observe.db.DataSource; +import fr.ird.observe.services.ObserveServiceFactory; +import fr.ird.observe.services.operation.ObsoleteReferenceToReplace; import fr.ird.observe.ui.admin.AdminActionModel; import fr.ird.observe.ui.admin.AdminStep; import org.nuiton.topia.persistence.TopiaEntity; @@ -29,9 +33,7 @@ import org.nuiton.topia.persistence.util.DiffState; import org.nuiton.topia.persistence.util.TopiaEntityRef; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.SortedMap; /** @@ -49,10 +51,7 @@ public class SynchronizeModel extends AdminActionModel { protected DiffState.DiffStateMap diff; /** liste des actions utilisateurs */ - protected List<SynchronizeUIHandler.ObsoleteRefReplaceAction> replaceActions; - - /** Universe of entities to update and with their topiaVersion to set. */ - protected Map<TopiaEntity, Long> versionsToUpdate; + protected List<ObsoleteReferenceToReplace> replaceActions; /** data source we want to synchronize. */ protected DataSource source; @@ -60,9 +59,13 @@ public class SynchronizeModel extends AdminActionModel { /** data source which contains central referentiel. */ protected DataSource centralSource; - /** temporary source where to make objectOperations. */ + /** temporary source where to make operations. */ protected DataSource tmpSource; + protected ObserveServiceFactory serviceFactory; + + protected ObserveServiceFactory tmpServiceFactory; + public SynchronizeModel() { super(AdminStep.SYNCHRONIZE); } @@ -83,33 +86,22 @@ public class SynchronizeModel extends AdminActionModel { this.diff = diff; } - public List<SynchronizeUIHandler.ObsoleteRefReplaceAction> getReplaceActions() { + public List<ObsoleteReferenceToReplace> getReplaceActions() { if (replaceActions == null) { - replaceActions = new ArrayList<SynchronizeUIHandler.ObsoleteRefReplaceAction>(); + replaceActions = new ArrayList<ObsoleteReferenceToReplace>(); } return replaceActions; } - public void setReplaceActions(List<SynchronizeUIHandler.ObsoleteRefReplaceAction> replaceActions) { - this.replaceActions = replaceActions; - } - - public Map<TopiaEntity, Long> getVersionsToUpdate() { - if (versionsToUpdate == null) { - versionsToUpdate = new HashMap<TopiaEntity, Long>(); - } - return versionsToUpdate; - } - - public void setVersionsToUpdate(Map<TopiaEntity, Long> versionsToUpdate) { - this.versionsToUpdate = versionsToUpdate; - } - public DataSource getSource() { return source; } public void setSource(DataSource source) { + if (serviceFactory != null) { + serviceFactory.close(); + serviceFactory = null; + } this.source = source; } @@ -126,6 +118,41 @@ public class SynchronizeModel extends AdminActionModel { } public void setTmpSource(DataSource tmpSource) { + if (tmpServiceFactory != null) { + tmpServiceFactory.close(); + tmpServiceFactory = null; + } this.tmpSource = tmpSource; } + + public ObserveServiceFactory getServiceFactory() { + + if (serviceFactory == null) { + Preconditions.checkNotNull(source, "Can't create source service factory if source is null"); + serviceFactory = ObserveContext.newServiceFactory(source); + } + return serviceFactory; + + } + + public ObserveServiceFactory getTmpServiceFactory() { + + if (tmpServiceFactory == null) { + Preconditions.checkNotNull(source, "Can't create source service factory if tmpSource is null"); + tmpServiceFactory = ObserveContext.newServiceFactory(tmpSource); + } + return tmpServiceFactory; + + } + + @Override + public void destroy() { + + super.destroy(); + setSource(null); + setTmpSource(null); + setCentralSource(null); + + } + } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/SynchronizeUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/SynchronizeUIHandler.java index c5671e0..17ccb98 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/SynchronizeUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/SynchronizeUIHandler.java @@ -22,12 +22,15 @@ package fr.ird.observe.ui.admin.synchronize; import fr.ird.observe.DecoratorService; -import fr.ird.observe.ObserveDAOHelper; +import fr.ird.observe.ObserveContext; import fr.ird.observe.ObserveEntityEnum; import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.seine.TripSeine; +import fr.ird.observe.services.ObserveServiceFactory; +import fr.ird.observe.services.ReplicationService; +import fr.ird.observe.services.operation.ObsoleteReferenceToReplace; +import fr.ird.observe.services.operation.SynchronizeService; +import fr.ird.observe.services.referential.ReferentialService; import fr.ird.observe.ui.UIHelper; import fr.ird.observe.ui.admin.AdminStep; import fr.ird.observe.ui.admin.AdminTabUI; @@ -38,17 +41,13 @@ import jaxx.runtime.swing.editor.MyDefaultCellEditor; import jaxx.runtime.swing.editor.bean.BeanComboBox; import jaxx.runtime.swing.wizard.ext.WizardState; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.jxpath.JXPathContext; +import org.apache.commons.collections4.MapUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.decorator.Decorator; import org.nuiton.decorator.JXPathDecorator; -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.util.DiffState; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; import org.nuiton.topia.persistence.util.TopiaEntityRef; import javax.swing.DefaultListModel; @@ -304,6 +303,7 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { box.addPropertyChangeListener( "selectedItem", new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { updateCanApply(); @@ -320,6 +320,7 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { addAdminWorker( getUi().getStartAction().getToolTipText(), new Callable<WizardState>() { + @Override public WizardState call() throws Exception { return doAction(); @@ -344,19 +345,16 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { openSource(source); openSource(centralSource); + ObserveServiceFactory sourceServiceFactory = getStepModel().getServiceFactory(); + SynchronizeService synchronizeService = sourceServiceFactory.getService(SynchronizeService.class); + // construction du différentiel - sendMessage(t("observe.message.synchro.build.diff", - centralSource.getLabel())); + sendMessage(t("observe.message.synchro.build.diff", centralSource.getLabel())); - DiffState.DiffStateMap diff = - getDataService().buildReferentielDifferentiel(centralSource, - source, - this - ); + DiffState.DiffStateMap diff = synchronizeService.buildReferentielDifferentiel(centralSource, this); getStepModel().setDiff(diff); - if (diff.isEmpty() || - CollectionUtils.isEmpty(diff.get(DiffState.REMOVED))) { + if (diff.isEmpty() || CollectionUtils.isEmpty(diff.get(DiffState.REMOVED))) { // aucune modification du référentiel // ou aucune entité obsolète @@ -370,16 +368,16 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { // detection des entités obsoletes - SortedMap<TopiaEntity, List<TopiaEntityRef>> obsoleteRefs = - detectObsoleteEntities(); + SortedMap<TopiaEntity, List<TopiaEntityRef>> obsoleteRefs = synchronizeService.detectObsoleteEntities(diff); getStepModel().setObsoleteRefs(obsoleteRefs); - if (obsoleteRefs == null || obsoleteRefs.isEmpty()) { + if (MapUtils.isNotEmpty(obsoleteRefs)) { reportSuccess(); // pas de reference obsolete a traiter return WizardState.SUCCESSED; + } // il existe des entités obsolètes utilisées dans la base locale @@ -387,11 +385,9 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { // on conserve la liste complète des entités qui utilisent des // référentiels obsolètes (on va les recopier plus tard) - List<TopiaEntity> obsoleteEntities = - new ArrayList<TopiaEntity>(obsoleteRefs.keySet()); + List<TopiaEntity> obsoleteEntities = new ArrayList<TopiaEntity>(obsoleteRefs.keySet()); - // on filtre les entités obsolètes directes (les seuls que l'utilisateur - // peut changer) + // on filtre les entités obsolètes directes (les seuls que l'utilisateur peut changer) removeUndirectObsoleteRefs(); @@ -401,29 +397,32 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { // pas de reference obsolete directe a traiter return WizardState.SUCCESSED; + } // dernier cas (le seul demandant une intervention humaine) - // il y a des références obsolètes directes sur des données observers + // il y a des références obsolètes directes sur des données - // on mets en place une base temporaire pour effectuer les corrections + // on met en place une base temporaire pour effectuer les corrections - sendMessage( - t("observe.message.synchro.create.temporary.db.to.resolve.obsoletes")); + sendMessage(t("observe.message.synchro.create.temporary.db.to.resolve.obsoletes")); DataSource tmpSource = model.getSafeTmpSource(false); getStepModel().setTmpSource(tmpSource); openSource(tmpSource); + ObserveServiceFactory tmpServiceFactory = getStepModel().getTmpServiceFactory(); + ReplicationService service = tmpServiceFactory.getService(ReplicationService.class); + // duplication du referentiel à jour vers la base temporaire - replicateReferentiel(centralSource, tmpSource); + service.replicateReferentiel(centralSource); // duplication des objets de la base locale qui utilisent les données obsolètes - replicateObsoletesEntities(obsoleteEntities, source, tmpSource); + service.replicateObsoletesEntities(obsoleteEntities, source, this); - // on injecte toutes les donnes utilisateurs dans la base de synchro - // car on va ensuite remplacer - replicateData(source, tmpSource); + //FIXME Il faut trouver exactement quelles données utilises des réferentiels obsolète et ne répliquer que ceux là + // on injecte toutes les donnes utilisateurs dans la base de synchro car on va ensuite remplacer + service.replicateAllData(source); // la synchronisation demande des modification de la base locale // on enregistre cette action aupres de l'action de sauvegarde @@ -432,9 +431,11 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { sendMessage(t("observe.message.synchro.operation.needFix")); return WizardState.NEED_FIX; + } public void reportSuccess() { + boolean needSave = false; DiffState.DiffStateMap diff = getStepModel().getDiff(); @@ -443,9 +444,7 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { if (!CollectionUtils.isEmpty(ids)) { // des doonées ont ete supprimées du referentiel distant needSave = true; - sendMessage( - t("observe.message.synchro.referentiel.was.removed", - ids.size())); + sendMessage(t("observe.message.synchro.referentiel.was.removed", ids.size())); for (String id : ids) { sendMessage(" - " + id); } @@ -455,8 +454,7 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { if (!CollectionUtils.isEmpty(ids)) { // des données ont ete ajoutees au referentiel distant needSave = true; - sendMessage(t("observe.message.synchro.referentiel.was.added", - ids.size())); + sendMessage(t("observe.message.synchro.referentiel.was.added", ids.size())); for (String id : ids) { sendMessage(" - " + id); } @@ -466,9 +464,7 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { if (!CollectionUtils.isEmpty(ids)) { // des doonées ont ete modifiees dans le referentiel distant needSave = true; - sendMessage( - t("observe.message.synchro.referentiel.was.modified", - ids.size())); + sendMessage(t("observe.message.synchro.referentiel.was.modified", ids.size())); for (String id : ids) { sendMessage(" - " + id); } @@ -476,64 +472,27 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { if (needSave) { // des données doivent être transférer vers la base locale - model.getSaveLocalModel().addStepForSave( - AdminStep.SYNCHRONIZE); + model.getSaveLocalModel().addStepForSave(AdminStep.SYNCHRONIZE); sendMessage(t("observe.message.synchro.local.modification")); - sendMessage( - t("observe.message.synchro.no.referentiel.conflict")); + sendMessage(t("observe.message.synchro.no.referentiel.conflict")); } else { sendMessage(t("observe.message.synchro.ref.is.updtodate")); } - sendMessage( - t("observe.message.synchro.operation.done", new Date())); - } - - protected SortedMap<TopiaEntity, List<TopiaEntityRef>> detectObsoleteEntities() throws Exception { - - DiffState.DiffStateMap diff = getStepModel().getDiff(); - - DataSource source = getStepModel().getSource(); - - // detection des entites obsoletes - - List<String> removedList = diff.get(DiffState.REMOVED); - - String[] ids = removedList.toArray(new String[removedList.size()]); - - TopiaContext tx = beginTransaction(source, "detectObsoleteRefs"); - - // detection des entites obsoletes - - try { - // des suppressions ont ete detectees, on doit retrouver - // dans la base locale les entites utilisant ces entites - // obsoletes - List<TripSeine> marees = ObserveDAOHelper.getTripSeineDAO(tx).findAll(); - - ObserveEntityEnum[] contracts = ObserveDAOHelper.getContracts(); - - SortedMap<TopiaEntity, List<TopiaEntityRef>> result; + sendMessage(t("observe.message.synchro.operation.done", new Date())); - result = TopiaEntityHelper.detectReferences(contracts, ids, marees); - return result; - } finally { - closeTransaction(source, tx, "detectObsoleteRefs"); - } } protected void removeUndirectObsoleteRefs() { Iterator<Map.Entry<TopiaEntity, List<TopiaEntityRef>>> itr; - SortedMap<TopiaEntity, List<TopiaEntityRef>> obsoleteRefs = - getStepModel().getObsoleteRefs(); + SortedMap<TopiaEntity, List<TopiaEntityRef>> obsoleteRefs = getStepModel().getObsoleteRefs(); for (itr = obsoleteRefs.entrySet().iterator(); itr.hasNext(); ) { Map.Entry<TopiaEntity, List<TopiaEntityRef>> entry = itr.next(); - for (Iterator<TopiaEntityRef> itrRef = - entry.getValue().iterator(); itrRef.hasNext(); ) { + for (Iterator<TopiaEntityRef> itrRef = entry.getValue().iterator(); itrRef.hasNext(); ) { TopiaEntityRef ref = itrRef.next(); TopiaEntity refInvoker = ref.getInvoker(); if (refInvoker == null) { @@ -546,10 +505,8 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { continue; } - ObserveEntityEnum refConstant = - ObserveEntityEnum.valueOf(refInvoker); - if (!Entities.DATA_ENTITIES_LIST.contains( - refConstant)) { + ObserveEntityEnum refConstant = ObserveEntityEnum.valueOf(refInvoker); + if (!Entities.DATA_ENTITIES_LIST.contains(refConstant)) { // on peut supprimer cette référence itrRef.remove(); if (log.isTraceEnabled()) { @@ -562,132 +519,59 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { // references dessus itr.remove(); if (log.isDebugEnabled()) { - log.debug("remove obsolete entity (not direct " + - "referentiel) : " + - entry.getKey().getTopiaId()); + log.debug("remove obsolete entity (not direct referentiel) : " + entry.getKey().getTopiaId()); } } } } - protected void replicateObsoletesEntities( - List<TopiaEntity> obsoleteEntities, - DataSource source, - DataSource tmpSource) throws Exception { - - String txName = "replicateObsoletesEntities"; - TopiaContext sourceCtxt = beginTransaction(source, txName); - try { - TopiaContext tmpCtxt = beginTransaction(tmpSource, txName); - try { - for (ObserveEntityEnum constant : Entities.REFERENCE_ENTITIES) { - Class<? extends TopiaEntity> contractClass = - constant.getContract(); - List<TopiaEntity> toReplicate = new ArrayList<TopiaEntity>(); - for (Iterator<TopiaEntity> itr = - obsoleteEntities.iterator(); itr.hasNext(); ) { - TopiaEntity e = itr.next(); - if (contractClass.isAssignableFrom(e.getClass())) { - if (log.isDebugEnabled()) { - log.debug("obsolete to inject : " + - e.getTopiaId()); - } - itr.remove(); - - // cet objet doit etre replique - toReplicate.add(e); - - sendMessage(t("observe.message.synchro.obsolete.data.to.duplicate", e)); - } - } - if (toReplicate.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("no obsolete entity " + constant); - } - continue; - } + public List<?> getEntityListFromSynchroDB(Class<?> type, boolean removeObsoletes) { - if (log.isDebugEnabled()) { - log.debug("inject obsolete entity " + constant + " (" + - toReplicate.size() + ")"); - } - sourceCtxt.replicateEntities(tmpCtxt, toReplicate); - commitTransaction(tmpSource, tmpCtxt, txName); - } + ObserveServiceFactory tmpServiceFactory = getStepModel().getTmpServiceFactory(); - } finally { - closeTransaction(tmpSource, tmpCtxt, txName); - } - } finally { - closeTransaction(source, sourceCtxt, txName); - } + ReferentialService service = tmpServiceFactory.getService(ReferentialService.class); + ObserveEntityEnum constant = ObserveEntityEnum.valueOf(type); + List<?> list = service.getList(constant.getContract()); - if (!obsoleteEntities.isEmpty()) { - throw new IllegalStateException( - "there is still obsolete entities to inject in " + - "synchro db : " + obsoleteEntities); - } - } - - public List<?> getEntityListFromSynchroDB(Class<?> type, - boolean removeObsoletes) { - - DataSource tmpSource = getStepModel().getTmpSource(); - List<?> list; - try { - ObserveEntityEnum constant = ObserveEntityEnum.valueOf(type); - list = getDataService().getList(tmpSource, constant.getContract()); - } catch (DataSourceException ex) { - //TODO should do better... - if (log.isErrorEnabled()) { - log.error(ex); - } - list = new ArrayList(); - } if (removeObsoletes) { DiffState.DiffStateMap diff = getStepModel().getDiff(); List<String> removedList = diff.get(DiffState.REMOVED); for (Iterator<?> itr = list.iterator(); itr.hasNext(); ) { + TopiaEntity e = (TopiaEntity) itr.next(); if (removedList.contains(e.getTopiaId())) { - // c'est une entite qui est obsolete, l'utilisateur - // ne peut pas l'utiliser + // c'est une entite qui est obsolete, l'utilisateur ne peut pas l'utiliser itr.remove(); } + } + } + return list; + } - public void resolvObsoleteReferences(TopiaEntity obsoleteRef, - List<TopiaEntityRef> refs, - TopiaEntity safeRef) { + public void resolvObsoleteReferences(TopiaEntity obsoleteRef, List<TopiaEntityRef> refs, TopiaEntity safeRef) { - ObsoleteRefReplaceAction action = new ObsoleteRefReplaceAction( - obsoleteRef.getTopiaId(), - safeRef.getTopiaId(), - refs); + ObsoleteReferenceToReplace action = new ObsoleteReferenceToReplace(obsoleteRef.getTopiaId(), safeRef.getTopiaId(), refs); SynchronizeModel stepModel = getStepModel(); stepModel.getReplaceActions().add(action); - SortedMap<TopiaEntity, List<TopiaEntityRef>> obsoleteRefs = - stepModel.getObsoleteRefs(); + SortedMap<TopiaEntity, List<TopiaEntityRef>> obsoleteRefs = stepModel.getObsoleteRefs(); List<TopiaEntityRef> globalRefs = obsoleteRefs.get(obsoleteRef); DataSource tmpSource = stepModel.getTmpSource(); - String txName = "resolvObsoleteReferences"; - TopiaContext tx = null; + ObserveServiceFactory serviceFactory = ObserveContext.newServiceFactory(tmpSource); try { - tx = beginTransaction(tmpSource, txName); + ReferentialService service = serviceFactory.getService(ReferentialService.class); - action.doAction(tx); - - commitTransaction(tmpSource, tx, txName); + service.replaceObsoleteReference(action); // on supprime toutes les références traitées globalRefs.removeAll(refs); @@ -701,129 +585,33 @@ public class SynchronizeUIHandler extends AdminTabUIHandler { obsoleteRefs.remove(obsoleteRef); if (log.isDebugEnabled()) { - log.debug("remove resolved obsolete property from temp " + - "db : " + obsoleteRef.getTopiaId()); + log.debug("remove resolved obsolete property from temp db : " + obsoleteRef.getTopiaId()); } - obsoleteRef = tx.findByTopiaId(obsoleteRef.getTopiaId()); - - // on peut la supprimer de la base temporaire - getDAO(tx, obsoleteRef).delete(obsoleteRef); + service.deleteEntities(Collections.singletonList(obsoleteRef.getTopiaId())); ui.firePropertyChange("obsoleteResolved", null, obsoleteRef); } - commitTransaction(tmpSource, tx, txName); - if (obsoleteRefs.isEmpty()) { - sendMessage( - t("observe.message.synchro.operation.done", new Date())); + sendMessage(t("observe.message.synchro.operation.done", new Date())); - // plus de references obsoletes a resoudre, l'action est - // terminée + // plus de references obsoletes a resoudre, l'action est terminée model.setStepState(WizardState.SUCCESSED); - } - } catch (Exception e) { - model.setStepState(onError(e)); - } finally { - try { - if (tx != null) { - closeTransaction(tmpSource, tx, txName); - } - } catch (DataSourceException e) { - model.setStepState(onError(e)); } - } - } - - public class ObsoleteRefReplaceAction { - - /** l'id de l'entité à remplacer */ - String obsoleteId; - - /** l'id de l'entité de remplacement */ - String safeId; - - /** la liste des références à traiter */ - TopiaEntityRef[] refs; - - ObsoleteRefReplaceAction(String obsoleteId, - String safeId, - List<TopiaEntityRef> refs) { - this.obsoleteId = obsoleteId; - this.refs = refs.toArray(new TopiaEntityRef[refs.size()]); - this.safeId = safeId; - } - - public void doAction(TopiaContext tx) throws TopiaException { - - if (log.isInfoEnabled()) { - log.info("load obsolete object " + obsoleteId); - } - - if (log.isInfoEnabled()) { - log.info("load safe object " + safeId); - } - - TopiaEntity safeRef = tx.findByTopiaId(safeId); - // on remplace les references - for (TopiaEntityRef ref : refs) { - TopiaEntity invoker = ref.getInvoker(); - - if (invoker == null) { - throw new NullPointerException( - "can not have a null invoker in " + ref); - } - - if (log.isInfoEnabled()) { - log.info("load invoker object " + invoker.getTopiaId()); - } - - invoker = tx.findByTopiaId(invoker.getTopiaId()); - - // switch entity - - String path = ref.getInvokerProperty(); - - JXPathContext jxcontext = JXPathContext.newContext(invoker); - - TopiaEntity oldValue = (TopiaEntity) jxcontext.getValue(path); - - if (log.isDebugEnabled()) { - log.debug("property to switch " + path + " old : " + - oldValue); - } + } catch (Exception e) { - if (log.isInfoEnabled()) { - log.info("change path : " + path); - log.info("old value : " + oldValue.getTopiaId()); - } + model.setStepState(onError(e)); - jxcontext.setValue(path, safeRef); + } finally { - TopiaEntity newValue = (TopiaEntity) jxcontext.getValue(path); + serviceFactory.close(); - if (log.isInfoEnabled()) { - log.info("new value : " + newValue.getTopiaId()); - } - if (log.isDebugEnabled()) { - log.debug("property to switch " + path + " new : " + - safeRef); - log.debug("property to switch " + path + " new Check : " + - newValue); - } - TopiaDAO<TopiaEntity> dao = getDAO(tx, invoker); - - dao.update(invoker); - } } - public String getObsoleteId() { - return obsoleteId; - } } } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUIHandler.java index f6b84da..f8abf5c 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUIHandler.java @@ -22,14 +22,15 @@ package fr.ird.observe.ui.admin.validate; import com.google.common.base.Charsets; -import fr.ird.observe.DataService; import fr.ird.observe.DecoratorService; +import fr.ird.observe.ObserveContext; import fr.ird.observe.ObserveServiceHelper; import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.services.model.DataSelectionModel; import fr.ird.observe.entities.referentiel.Program; import fr.ird.observe.entities.seine.TripSeine; +import fr.ird.observe.services.ObserveServiceFactory; +import fr.ird.observe.services.operation.ValidationService; +import fr.ird.observe.services.model.DataSelectionModel; import fr.ird.observe.ui.UIHelper; import fr.ird.observe.ui.admin.AdminStep; import fr.ird.observe.ui.admin.AdminTabUI; @@ -50,9 +51,6 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.util.TopiaEntityRef; import org.nuiton.validator.NuitonValidatorScope; import org.nuiton.validator.bean.simple.SimpleBeanValidator; @@ -137,6 +135,7 @@ public class ValidateUIHandler extends AdminTabUIHandler { final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); getModel().getValidateModel().addPropertyChangeListener(ValidateModel.PROPERTY_MODEL_MODE, new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { ValidationModelMode value = (ValidationModelMode) evt.getNewValue(); @@ -169,6 +168,7 @@ public class ValidateUIHandler extends AdminTabUIHandler { }); selectTabUI.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { AdminUIModel model = (AdminUIModel) evt.getSource(); @@ -305,6 +305,7 @@ public class ValidateUIHandler extends AdminTabUIHandler { addAdminWorker( ((ValidateUI) ui).getStartButton().getToolTipText(), new Callable<WizardState>() { + @Override public WizardState call() throws Exception { return doAction(); @@ -348,7 +349,6 @@ public class ValidateUIHandler extends AdminTabUIHandler { protected WizardState initDB() throws Exception { - // on recupere la source de données source = getSource(); @@ -365,8 +365,7 @@ public class ValidateUIHandler extends AdminTabUIHandler { ValidateModel validationModel = model.getValidateModel(); ValidatorsMap validators = validationModel.getValidators(); - sendMessage(t("observe.message.validation.use.storage", - source.getLabel())); + sendMessage(t("observe.message.validation.use.storage", source.getLabel())); sendMessage(t("observe.message.validation.prepare.validators")); @@ -378,14 +377,18 @@ public class ValidateUIHandler extends AdminTabUIHandler { String label = t(DecoratorService.getEntityLabel(v.getType())); sendMessage(t("observe.message.validation.detected", label)); } + } else { + sendMessage(t("observe.message.no.validation.detected")); + } return null; + } - public void launchValidation() throws Exception { + public void launchValidation() { // on vide les anciens messages ValidateModel stepModel = model.getValidateModel(); @@ -393,101 +396,117 @@ public class ValidateUIHandler extends AdminTabUIHandler { ValidatorsMap validators = stepModel.getValidators(); - ValidationMessageDetector detector = - new ValidationMessageDetector(validators); + ValidationMessageDetector detector = new ValidationMessageDetector(validators); DataSelectionModel dataModel = model.getSelectionDataModel(); ValidationContext context = ObserveServiceHelper.getValidationContext(); context.setDataSource(model.getLocalSource()); - context.setDataContext(model.getDataService().getDataContext()); + context.setDataContext(model.getDataContext()); - TopiaContext ctxt = beginTransaction(source, "launchValidation"); + ObserveServiceFactory serviceFactory = ObserveContext.newServiceFactory(source); +// TopiaContext ctxt = beginTransaction(source, "launchValidation"); try { + ValidationService service = serviceFactory.getService(ValidationService.class); - if (dataModel.isUseReferentiel()) { - - // validation des referentiels selectionnes - - validateReferentiel(detector, ctxt, dataModel); - } + service.validate(this, detector, dataModel); - if (dataModel.isUseData()) { +// if (dataModel.isUseReferentiel()) { +// +// // validation des referentiels selectionnes +// +// validateReferentiel(detector, ctxt, dataModel); +// } +// +// if (dataModel.isUseData()) { +// +// // validation des donnees observateur selectionnee +// +// validateData(detector, ctxt, dataModel); +// } - // validation des donnees observateur selectionnee + } finally { - validateData(detector, ctxt, dataModel); - } + serviceFactory.close(); - } finally { context.setDataSource(null); SortedMap<TopiaEntityRef, List<SimpleBeanValidatorMessage<?>>> refs = detector.getRefs(); stepModel.setMessages(refs); detector.clear(); - closeTransaction(source, ctxt, "launchValidation"); - } - } - - private void validateData(ValidationMessageDetector detector, - TopiaContext ctxt, - DataSelectionModel dataModel) throws TopiaException { - Set<String> data = dataModel.getSelectedData(); +// closeTransaction(source, ctxt, "launchValidation"); - for (String id : data) { - TripSeine e = (TripSeine) ctxt.findByTopiaId(id); - Program p = e.getProgram(); - sendMessage(t("observe.message.validation.start.maree", dTrip.toString(e), dProgram.toString(p))); - detector.detectMessages(e); } } - protected void validateReferentiel(ValidationMessageDetector detector, - TopiaContext ctxt, - DataSelectionModel dataModel) throws DataSourceException, TopiaException { - - DataService dataService = getDataService(); - Set<Class<?>> classes = dataModel.getSelectedReferentiel(); - - for (Class<?> klass : classes) { - // on recupere la liste des ids a valider - Class<? extends TopiaEntity> refClass = (Class<? extends TopiaEntity>) klass; - List<String> ids = dataService.getEntityIds(source, refClass); - String entityLabel = t(DecoratorService.getEntityLabel(klass)); - sendMessage(t("observe.message.validation.start.referentiel", entityLabel, ids.size())); - for (String id : ids) { - TopiaEntity e = ctxt.findByTopiaId(id); - detector.detectMessages(e); - } - ids.clear(); - } - } +// private void validateData(ValidationMessageDetector detector, +// TopiaContext ctxt, +// DataSelectionModel dataModel) throws TopiaException { +// Set<String> data = dataModel.getSelectedData(); +// +// for (String id : data) { +// TripSeine e = (TripSeine) ctxt.findByTopiaId(id); +// Program p = e.getProgram(); +// sendMessage(t("observe.message.validation.start.maree", dTrip.toString(e), dProgram.toString(p))); +// detector.detectMessages(e); +// } +// } +// +// protected void validateReferentiel(ValidationMessageDetector detector, +// TopiaContext ctxt, +// DataSelectionModel dataModel) throws DataSourceException, TopiaException { +// +// DataService dataService = getDataService(); +// Set<Class<?>> classes = dataModel.getSelectedReferentiel(); +// +// for (Class<?> klass : classes) { +// // on recupere la liste des ids a valider +// Class<? extends TopiaEntity> refClass = (Class<? extends TopiaEntity>) klass; +// List<String> ids = dataService.getEntityIds(source, refClass); +// String entityLabel = t(DecoratorService.getEntityLabel(klass)); +// sendMessage(t("observe.message.validation.start.referentiel", entityLabel, ids.size())); +// for (String id : ids) { +// TopiaEntity e = ctxt.findByTopiaId(id); +// detector.detectMessages(e); +// } +// ids.clear(); +// } +// } public void saveReport() { + WizardState finalState = null; ValidateModel validationModel = model.getValidateModel(); try { - if (validationModel.isGenerateReport()) { - sendMessage( - t("observe.message.validation.save.report", validationModel.getReportFile())); + if (validationModel.isGenerateReport()) { + sendMessage(t("observe.message.validation.save.report", validationModel.getReportFile())); generateReportFile(validationModel); + } else { - sendMessage( - t("observe.message.validation.not.save.report")); + + sendMessage(t("observe.message.validation.not.save.report")); + } finalState = WizardState.SUCCESSED; + } catch (Exception e) { + validationModel.setError(e); finalState = WizardState.FAILED; + } finally { + model.setStepState(AdminStep.VALIDATE, finalState); + } + } public void generateReportFile(ValidateModel validationModel) throws IOException { + File reportFile = validationModel.getReportFile(); if (log.isInfoEnabled()) { log.info("save report in " + reportFile); @@ -507,8 +526,7 @@ public class ValidateUIHandler extends AdminTabUIHandler { TopiaEntityRef ref = entry.getKey(); String refStr = service.decorate(ref.getRef()); List<SimpleBeanValidatorMessage<?>> refMessages = entry.getValue(); - EnumSet<NuitonValidatorScope> scopes = - SimpleBeanValidators.getScopes(refMessages); + EnumSet<NuitonValidatorScope> scopes = SimpleBeanValidators.getScopes(refMessages); builder.append(t("observe.validation.report.entity", ref.getRef().getTopiaId(), refStr, refMessages.size(), scopes)).append('\n'); for (NuitonValidatorScope scope : scopes) { List<SimpleBeanValidatorMessage<?>> messagesByScope = filterMessages(scope, refMessages); @@ -525,9 +543,11 @@ public class ValidateUIHandler extends AdminTabUIHandler { log.info(content); } FileUtils.write(reportFile, content, Charsets.UTF_8.name()); + } private List<SimpleBeanValidatorMessage<?>> filterMessages(NuitonValidatorScope scope, List<SimpleBeanValidatorMessage<?>> refMessages) { + List<SimpleBeanValidatorMessage<?>> result = new ArrayList<SimpleBeanValidatorMessage<?>>(); for (SimpleBeanValidatorMessage<?> message : refMessages) { if (message.getScope().equals(scope)) { @@ -535,13 +555,15 @@ public class ValidateUIHandler extends AdminTabUIHandler { } } return result; + } // ------------------------------------------------------------------------ - // -- ValidateConfgUI methods + // -- ValidateConfigUI methods // ------------------------------------------------------------------------ public void updateValidationScopes(JCheckBox checkBox) { + NuitonValidatorScope scope = getValidatorScope(checkBox); ValidateModel validateModel = getModel().getValidateModel(); if (checkBox.isSelected()) { @@ -551,6 +573,7 @@ public class ValidateUIHandler extends AdminTabUIHandler { // supprime le scope validateModel.removeScope(scope); } + } public ComboBoxModel updateComboModel(Object... datas) { @@ -570,10 +593,6 @@ public class ValidateUIHandler extends AdminTabUIHandler { return t("observe.common.selected.validators", validateModel.getValidators().size()); } - public AdminStep getObjectOperation(JCheckBox checkBox) { - return AdminStep.valueOf(checkBox.getName()); - } - public NuitonValidatorScope getValidatorScope(JCheckBox checkBox) { return (NuitonValidatorScope) checkBox.getClientProperty("value"); } @@ -583,11 +602,6 @@ public class ValidateUIHandler extends AdminTabUIHandler { return scopes.contains(scope); } - public boolean isObjectOperationSelected(Set<AdminStep> objectOperations, JCheckBox checkBox) { - AdminStep scope = getObjectOperation(checkBox); - return objectOperations.contains(getObjectOperation(checkBox)); - } - public void chooseValidationReportFile(ValidateConfigUI configUI) { File f = UIHelper.chooseDirectory( configUI, @@ -606,13 +620,4 @@ public class ValidateUIHandler extends AdminTabUIHandler { getModel().getValidateModel().setReportFile(new File(configUI.validationReportDirectoryText.getText(), filename)); } - public String updateReferentielPolicy(boolean valid) { - if (!valid) { - return t("observe.common.storage.not.valid"); - } else { - return model.getCentralSourceModel().getPgConfig().getPolicyLabel(); - } - } - - } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jaxx b/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jaxx index d88d4d8..b67bef9 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jaxx +++ b/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jaxx @@ -35,7 +35,6 @@ <import> fr.ird.observe.db.DataContext - fr.ird.observe.DataService fr.ird.observe.db.DataSource fr.ird.observe.ObserveConfig fr.ird.observe.ObserveContext @@ -61,9 +60,6 @@ <SwingValidatorMessageTableModel id='errorTableModel' initializer='getContextValue(SwingValidatorMessageTableModel.class)'/> - <DataService id='dataService' - initializer='getContextValue(DataService.class)'/> - <DataSource id='dataSource' initializer='ObserveContext.get().getDataSource()'/> diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUIHandler.java index 97a049e..23e3d01 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUIHandler.java @@ -50,8 +50,6 @@ import org.nuiton.decorator.Decorator; import org.nuiton.decorator.DecoratorUtil; import org.nuiton.decorator.JXPathDecorator; import org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.util.TopiaEntityBinder; import org.nuiton.validator.NuitonValidatorScope; @@ -357,16 +355,6 @@ public abstract class ContentUIHandler<E extends TopiaEntity> { return icon; } - protected void onLoad(TopiaContext tx, E bean) throws TopiaException { - - // par defaut on charge l'objet de la base dans le bean d'édition - getLoadBinder().load(bean, getBean(), true); - } - - protected E onPreCreate(TopiaContext tx, Object parentBean, E bean) throws TopiaException { - return bean; - } - public void startEditUI(String... binding) { E editBean = getBean(); diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUIInitializer.java b/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUIInitializer.java index 7d426a0..49ed247 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUIInitializer.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/content/ContentUIInitializer.java @@ -24,7 +24,6 @@ package fr.ird.observe.ui.content; import com.google.common.base.Predicate; import com.google.common.collect.Lists; -import fr.ird.observe.DataService; import fr.ird.observe.DecoratorService; import fr.ird.observe.ObserveContext; import fr.ird.observe.db.DataSourceException; @@ -679,8 +678,8 @@ public class ContentUIInitializer<E extends TopiaEntity, UI extends ObserveConte new EntityDoubleListPropertyChangeListener<E>(entityClass, list); //FIXME Remove this - DataService service = context.getDataService(); - service.addReferentielPropertyChangeListener(entityClass, listener); +// DataService service = context.getDataService(); +// service.addReferentielPropertyChangeListener(entityClass, listener); } /** @@ -735,8 +734,8 @@ public class ContentUIInitializer<E extends TopiaEntity, UI extends ObserveConte EntityListPropertyChangeListener<E> listener = new EntityListPropertyChangeListener<E>(entityClass, list); //FIXME Remove this!!! - DataService service = context.getDataService(); - service.addReferentielPropertyChangeListener(entityClass, listener); +// DataService service = context.getDataService(); +// service.addReferentielPropertyChangeListener(entityClass, listener); } /** @@ -838,7 +837,7 @@ public class ContentUIInitializer<E extends TopiaEntity, UI extends ObserveConte }; //FIXME Remove this - context.getDataService().addReferentielPropertyChangeListener(entityClass, listener); +// context.getDataService().addReferentielPropertyChangeListener(entityClass, listener); } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferentialContentUIInitializer.java b/observe-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferentialContentUIInitializer.java index f8abdd4..3ac17f4 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferentialContentUIInitializer.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferentialContentUIInitializer.java @@ -22,7 +22,6 @@ package fr.ird.observe.ui.content.ref; * #L% */ -import fr.ird.observe.DataService; import fr.ird.observe.DecoratorService; import fr.ird.observe.ObserveContext; import fr.ird.observe.db.DataSourceException; @@ -102,10 +101,9 @@ public class ReferentialContentUIInitializer<E extends ReferenceEntity, UI exten //FIXME Remove this!!! // listen on cache modification - EntityListPropertyChangeListener<E> listener = - new EntityListPropertyChangeListener<E>(entityClass, list); - DataService dataService = ObserveContext.get().getDataService(); - dataService.addReferentielPropertyChangeListener(entityClass, listener); +// EntityListPropertyChangeListener<E> listener = new EntityListPropertyChangeListener<E>(entityClass, list); +// DataService dataService = ObserveContext.get().getDataService(); +// dataService.addReferentielPropertyChangeListener(entityClass, listener); } @SuppressWarnings("unchecked") diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/storage/RemoteUILauncher.java b/observe-swing/src/main/java/fr/ird/observe/ui/storage/RemoteUILauncher.java index 01958be..03d750e 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/storage/RemoteUILauncher.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/storage/RemoteUILauncher.java @@ -21,8 +21,6 @@ */ package fr.ird.observe.ui.storage; -import fr.ird.observe.ObserveContext; -import fr.ird.observe.DataService; import fr.ird.observe.db.constants.DbMode; import fr.ird.observe.db.util.PGInstall; import fr.ird.observe.db.util.SecurityModel; @@ -160,7 +158,7 @@ public abstract class RemoteUILauncher extends StorageUILauncher { protected void applySecurity(PGInstall task) throws Exception { } - protected DataService getDataService() { - return ObserveContext.get().getDataService(); - } +// protected DataService getDataService() { +// return ObserveContext.get().getDataService(); +// } } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/storage/StorageBackupUILauncher.java b/observe-swing/src/main/java/fr/ird/observe/ui/storage/StorageBackupUILauncher.java index 5983460..ec33e90 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/storage/StorageBackupUILauncher.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/storage/StorageBackupUILauncher.java @@ -22,7 +22,6 @@ package fr.ird.observe.ui.storage; import fr.ird.observe.ObserveContext; -import fr.ird.observe.DataService; import fr.ird.observe.db.DataSource; import fr.ird.observe.db.constants.DbMode; import fr.ird.observe.db.impl.H2DataSource; @@ -111,7 +110,7 @@ public class StorageBackupUILauncher extends StorageUILauncher { return source; } - protected DataService getDataService() { - return ObserveContext.get().getDataService(); - } +// protected DataService getDataService() { +// return ObserveContext.get().getDataService(); +// } } diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIHandler.java b/observe-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIHandler.java index e34ad30..a90ebf8 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIHandler.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIHandler.java @@ -32,7 +32,6 @@ import fr.ird.observe.db.DataSource; import fr.ird.observe.db.DataSourceConfig; import fr.ird.observe.db.DataSourceException; import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.db.ReplicationService; import fr.ird.observe.db.constants.CreationMode; import fr.ird.observe.db.constants.DbMode; import fr.ird.observe.db.event.DataSourceEvent; @@ -95,14 +94,6 @@ public class StorageUIHandler { private static final Log log = LogFactory.getLog(StorageUIHandler.class); /** - * Service de replication. - * <p/> - * Note: le service est sans état et donc peut rester en état du handler. - */ - protected ReplicationService replicationService = - ObserveServiceHelper.newReplicationService(); - - /** * Prépare une service de persistance à partir d'un modèle. * <p/> * Le service ne sera pas ouvert. @@ -635,12 +626,23 @@ public class StorageUIHandler { tempStorage = ObserveServiceHelper.newEmptyTempStorage( config, t("observe.storage.label.backup"), - "tmpBackup_" + dst.getName() - ); + "tmpBackup_" + dst.getName()); tempStorage.doOpen(); - replicationService.replicateReferentiel(service, tempStorage); - replicationService.replicateAllData(service, tempStorage); + + ObserveServiceFactory serviceFactory = ObserveContext.newServiceFactory(tempStorage); + + try { + + fr.ird.observe.services.ReplicationService replicationService = serviceFactory.getService(fr.ird.observe.services.ReplicationService.class); + replicationService.replicateReferentiel(service); + replicationService.replicateAllData(service); + + } finally { + + serviceFactory.close(); + + } tempStorage.storeDB(dst); @@ -714,13 +716,23 @@ public class StorageUIHandler { tempStorage = ObserveServiceHelper.newEmptyTempStorage( config, t("observe.storage.label.backup"), - "tmpBackup_" + dst.getName() - ); + "tmpBackup_" + dst.getName()); tempStorage.doOpen(); - replicationService.replicateReferentiel(service, tempStorage); - replicationService.replicateData(service, tempStorage, mareeIds); + ObserveServiceFactory serviceFactory = ObserveContext.newServiceFactory(tempStorage); + + try { + + fr.ird.observe.services.ReplicationService replicationService = serviceFactory.getService(fr.ird.observe.services.ReplicationService.class); + replicationService.replicateReferentiel(service); + replicationService.replicateData(service, mareeIds); + + } finally { + + serviceFactory.close(); + + } tempStorage.storeDB(dst); diff --git a/observe-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractNodeChildLoador.java b/observe-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractNodeChildLoador.java index 489e9c4..42409b3 100644 --- a/observe-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractNodeChildLoador.java +++ b/observe-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractNodeChildLoador.java @@ -21,7 +21,6 @@ */ package fr.ird.observe.ui.tree.loadors; -import fr.ird.observe.DataService; import fr.ird.observe.DecoratorService; import fr.ird.observe.ObserveContext; import fr.ird.observe.services.model.DataSelectionModel; @@ -40,8 +39,6 @@ public abstract class AbstractNodeChildLoador<O> extends NavTreeNodeChildLoador< private static final long serialVersionUID = 1L; - protected transient DataService dataService; - protected AbstractNodeChildLoador(Class<O> beanType) { super(beanType); } @@ -52,15 +49,8 @@ public abstract class AbstractNodeChildLoador<O> extends NavTreeNodeChildLoador< return result; } - protected DataService getDataService() { - if (dataService == null) { - dataService = ObserveContext.get().getDataService(); - } - return dataService; - } - protected DecoratorService getDecoratorService() { - return getDataService().getDecoratorService(); + return ObserveContext.get().getDecoratorService(); } } -- To stop receiving notification emails like this one, please contact codelutin.com SCM administrator <admin+scm@list.forge.codelutin.com>.
participants (1)
-
codelutin.com scm