Tutti-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
February 2013
- 6 participants
- 236 discussions
Author: tchemit
Date: 2013-02-15 00:55:08 +0100 (Fri, 15 Feb 2013)
New Revision: 415
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/415
Log:
begin doc + update last nuiton-utils snapshot
Added:
trunk/src/site/rst/protocol.rst
trunk/src/site/rst/temporaryReferential.rst
trunk/src/site/rst/update.rst
Modified:
trunk/pom.xml
trunk/src/site/site_fr.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-02-14 23:53:34 UTC (rev 414)
+++ trunk/pom.xml 2013-02-14 23:55:08 UTC (rev 415)
@@ -124,7 +124,7 @@
<!-- libraries version -->
- <nuitonUtilsVersion>2.6.7</nuitonUtilsVersion>
+ <nuitonUtilsVersion>2.6.8-SNAPSHOT</nuitonUtilsVersion>
<nuitonI18nVersion>2.5</nuitonI18nVersion>
<eugenePluginVersion>2.6.1</eugenePluginVersion>
@@ -138,7 +138,7 @@
<slf4jVersion>1.7.2</slf4jVersion>
- <adagioVersion>3.3.1-SNAPSHOT</adagioVersion>
+ <adagioVersion>3.3.2-SNAPSHOT</adagioVersion>
<msaccessImporterVersion>1.4.1</msaccessImporterVersion>
Added: trunk/src/site/rst/protocol.rst
===================================================================
--- trunk/src/site/rst/protocol.rst (rev 0)
+++ trunk/src/site/rst/protocol.rst 2013-02-14 23:55:08 UTC (rev 415)
@@ -0,0 +1,30 @@
+.. -
+.. * #%L
+.. * Tutti
+.. * $Id$
+.. * $HeadURL$
+.. * %%
+.. * Copyright (C) 2012 - 2013 Ifremer
+.. * %%
+.. * 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%
+.. -
+
+
+====================
+Gestion du protocole
+====================
+
+TODO
\ No newline at end of file
Property changes on: trunk/src/site/rst/protocol.rst
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/src/site/rst/temporaryReferential.rst
===================================================================
--- trunk/src/site/rst/temporaryReferential.rst (rev 0)
+++ trunk/src/site/rst/temporaryReferential.rst 2013-02-14 23:55:08 UTC (rev 415)
@@ -0,0 +1,30 @@
+.. -
+.. * #%L
+.. * Tutti
+.. * $Id$
+.. * $HeadURL$
+.. * %%
+.. * Copyright (C) 2012 - 2013 Ifremer
+.. * %%
+.. * 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%
+.. -
+
+
+====================================
+Gestion des référentiels temporaires
+====================================
+
+TODO
\ No newline at end of file
Property changes on: trunk/src/site/rst/temporaryReferential.rst
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/src/site/rst/update.rst
===================================================================
--- trunk/src/site/rst/update.rst (rev 0)
+++ trunk/src/site/rst/update.rst 2013-02-14 23:55:08 UTC (rev 415)
@@ -0,0 +1,119 @@
+.. -
+.. * #%L
+.. * Tutti
+.. * $Id$
+.. * $HeadURL$
+.. * %%
+.. * Copyright (C) 2012 - 2013 Ifremer
+.. * %%
+.. * 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%
+.. -
+
+=======================
+Mise à jour du logiciel
+=======================
+
+Présentation
+------------
+
+**Tutti** utilise un mécanisme simple pour effectuer les mises à jour de ses
+différents composants, à savoir:
+
+1. Mise à jour de la JRE
+2. Mise à jour du programme Tutti
+3. Mise à jour des fichiers de traductions
+4. Mise à jour de la base de données.
+
+Principe des mises à jour
+-------------------------
+
+Chaque composant est contenu dans un répertoire et possède un fichier
+obligatoirement nommé **version.appup** qui contient la version du composant.
+
+Un fichier de propriétés disponible sur le réseau à l'adresse suivante:
+http://appup.forge.codelutin.com/tutti/update-tutti.properties
+
+contient la description des dernières version disponibles.
+
+::
+
+ ################################################################################
+ ### JRE Updates ################################################################
+ ################################################################################
+
+ jre.version=1.7.10
+ linux.amd64.jre.url=zip:http://nexus.nuiton.org/nexus/content/repositories/…
+ linux.i386.jre.url=zip:http://nexus.nuiton.org/nexus/content/repositories/j…
+ windows.amd64.jre.url=zip:http://nexus.nuiton.org/nexus/content/repositorie…
+ windows.i386.jre.url=zip:http://nexus.nuiton.org/nexus/content/repositories…
+
+ ################################################################################
+ ### Tutti Updates ##############################################################
+ ################################################################################
+
+ tutti.version=1.0-SNAPSHOT
+ tutti.url=zip:http://nexus.nuiton.org/nexus/content/repositories/other-rele…
+
+ ################################################################################
+ ### I18n Updates ###############################################################
+ ################################################################################
+
+ i18n.version=1.0-SNAPSHOT
+ i18n.url=zip:http://nexus.nuiton.org/nexus/content/repositories/other-relea…
+
+ ################################################################################
+ ### DB Updates #################################################################
+ ################################################################################
+
+ db.version=2013.02.02
+ db.url=zip:http://appup.forge.codelutin.com/tutti/auth/tutti-db-2013.02.02.…
+ db.auth=true
+
+Au démarrage de l'application le fichier est lu et si un des composants est
+plus récent dans la description du fichier de mises à jour, il est téléchargé
+puis l'application l'intègre.
+
+Chaque composant téléchargeable doit être un fichier zip (mais d'autre formats
+d'archivage sont possibles) et contenir un seul répertoire (il n'est pas
+possible d'avoir le composant directement à la racine de l'archive).
+
+Mettre en place une nouvelle mise à jour
+----------------------------------------
+
+Pour pouvoir définir une nouvelle mise à jour, il faut donc modifier le fichier
+de mises à jour :
+
+1. changer la version du composant
+2. changer l'url de téléchargement du composant.
+
+Mise à jour sécurisées
+----------------------
+
+La mise à jour de la base est sécurisée, à savoir que l'url d'accès au zip de
+la base requière un mot de passe.
+
+Le fichier de mise à jour quand à lui sera toujours disponible publiquement.
+
+Pré-requis à la création d'une nouvelle version de Tutti
+--------------------------------------------------------
+
+pour pouvoir créer une nouvelle version de Tutti, il nous faut connaitre la
+dernière mise à jour de la base.
+
+Ainsi nous pourrons monter les version du fichier de mise à jour automatiquement.
+
+Les autres composants (jre, tutti et i18n) sont automatiquement gérés lors de
+la création de la nouvelle version.
\ No newline at end of file
Property changes on: trunk/src/site/rst/update.rst
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/src/site/site_fr.xml
===================================================================
--- trunk/src/site/site_fr.xml 2013-02-14 23:53:34 UTC (rev 414)
+++ trunk/src/site/site_fr.xml 2013-02-14 23:55:08 UTC (rev 415)
@@ -96,7 +96,8 @@
<menu name="Tutti">
<item name="Accueil" href="index.html"/>
- <item name="Configuration" href="./application-config-report.html"/>
+ <item name="Gestion du protocole" href="./protocol.html"/>
+ <item name="Référentiels temporaires" href="./temporaryReferential.html"/>
<item name="Téléchargement"
href="http://forge.codelutin.com/projects/tutti/files"/>
<item name="Roadmap"
@@ -105,7 +106,9 @@
</menu>
<menu name="Documentation Technique">
+ <item name="Configuration" href="./application-config-report.html"/>
<item name="Référentiel" href="referential.html"/>
+ <item name="Mise à jour des versions" href="./update.html"/>
</menu>
<menu ref="reports"/>
1
0
r414 - in trunk/tutti-persistence: . src/main/java/fr/ifremer/tutti/persistence src/main/java/fr/ifremer/tutti/persistence/entities src/main/java/fr/ifremer/tutti/persistence/service src/main/java/fr/ifremer/tutti/persistence/service/synchro src/main/resources src/test/java/fr/ifremer/tutti/persistence src/test/java/fr/ifremer/tutti/persistence/service src/test/java/fr/ifremer/tutti/persistence/service/synchro
by tchemit@users.forge.codelutin.com 14 Feb '13
by tchemit@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: tchemit
Date: 2013-02-15 00:53:34 +0100 (Fri, 15 Feb 2013)
New Revision: 414
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/414
Log:
improve synchro (add progressionModel in result) + add missingsvnproperties,...
Added:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java
Modified:
trunk/tutti-persistence/pom.xml
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java
trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java
Modified: trunk/tutti-persistence/pom.xml
===================================================================
--- trunk/tutti-persistence/pom.xml 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/pom.xml 2013-02-14 23:53:34 UTC (rev 414)
@@ -88,6 +88,11 @@
<artifactId>commons-dbcp</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.swinglabs.swingx</groupId>
+ <artifactId>swingx-common</artifactId>
+ </dependency>
+
<!-- Yaml -->
<dependency>
Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -0,0 +1,101 @@
+package fr.ifremer.tutti.persistence;
+
+/*
+ * #%L
+ * Tutti :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import org.jdesktop.beans.AbstractSerializableBean;
+
+/**
+ * Simple model for a progression long task.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class ProgressionModel extends AbstractSerializableBean {
+
+ private static final long serialVersionUID = 1L;
+
+ public static final String PROPERTY_TOTAL = "total";
+
+ public static final String PROPERTY_CURRENT = "current";
+
+ public static final String PROPERTY_RATE = "rate";
+
+ public static final String PROPERTY_MESSAGE = "message";
+
+ protected int total;
+
+ protected int current;
+
+ protected float rate;
+
+ protected String message;
+
+ public long getTotal() {
+ return total;
+ }
+
+ public void setTotal(int total) {
+ Object oldValue = getTotal();
+ this.total = total;
+ firePropertyChange(PROPERTY_TOTAL, oldValue, total);
+ setCurrent(0);
+ }
+
+ public long getCurrent() {
+ return current;
+ }
+
+ public void setCurrent(int current) {
+ Object oldValue = getCurrent();
+ this.current = current;
+ firePropertyChange(PROPERTY_CURRENT, oldValue, current);
+ }
+
+ public void increments(int nb) {
+ setCurrent(current + nb);
+ setRate(getCurrent() / getTotal());
+ }
+
+ public float getRate() {
+ return rate;
+ }
+
+ public void setRate(float rate) {
+ Object oldValue = getRate();
+ this.rate = rate;
+ firePropertyChange(PROPERTY_RATE, oldValue, rate);
+
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ Object oldValue = getMessage();
+ this.message = message;
+ firePropertyChange(PROPERTY_MESSAGE, oldValue, message);
+ }
+}
Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -223,6 +223,10 @@
p.put(Environment.PASS, password);
}
+ public static String getJdbcUrl(File directory, String dbName) {
+ return "jdbc:hsqldb:file:" + directory.getAbsolutePath() + "/" + dbName;
+ }
+
protected static class IdPredicate<B extends IdAware> implements Predicate<B> {
private final String id;
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -1,8 +1,33 @@
-package fr.ifremer.tutti.persistence.service;
-
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional(readOnly = true)
-public interface BatchPersistenceService extends CatchBatchPersistenceService, SpeciesBatchPersistenceService{
-
-}
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional(readOnly = true)
+public interface BatchPersistenceService extends CatchBatchPersistenceService, SpeciesBatchPersistenceService {
+
+}
\ No newline at end of file
Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -1,1297 +1,1322 @@
-package fr.ifremer.tutti.persistence.service;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Serializable;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.annotation.Resource;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.FlushMode;
-import org.hibernate.type.IntegerType;
-import org.springframework.cache.annotation.CacheEvict;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.DataRetrievalFailureException;
-import org.springframework.stereotype.Service;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-
-import fr.ifremer.adagio.core.dao.data.batch.Batch;
-import fr.ifremer.adagio.core.dao.data.batch.CatchBatchExtendDao;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationError;
-import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException;
-import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidator;
-import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
-import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
-import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
-import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
-import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
-import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
-import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus;
-import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
-import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
-import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
-import fr.ifremer.tutti.persistence.entities.referential.Species;
-import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
-
-@Service("batchPersistenceService")
-public class BatchPersistenceServiceImpl
- extends AbstractPersistenceService implements BatchPersistenceService, CatchBatchValidator
- {
-
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(BatchPersistenceServiceImpl.class);
-
- @Resource(name = "referentialPersistenceService")
- protected ReferentialPersistenceService referentialService;
-
- @Resource(name = "denormalizedBatchDao")
- protected DenormalizedBatchDao denormalizedBatchDao;
-
- @Resource(name = "sortingBatchDao")
- protected SortingBatchDao sortingBatchDao;
-
- @Resource(name = "catchBatchDao")
- protected CatchBatchExtendDao catchBatchDao;
-
- @Resource(name = "measurementPersistenceHelper")
- protected MeasurementPersistenceHelper measurementHelper;
-
- @Override
- public void init() {
- super.init();
- catchBatchDao.registerCatchBatchValidator(this);
- }
-
- @Override
- public void close() {
- catchBatchDao.unregisterCatchBatchValidator(this);
- super.close();
- }
-
- @Override
- public boolean isEnable(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
- // Apply validation only on catch batch for fishingOperation
- return (catchBatch.getFishingOperation() != null);
- }
-
- @Override
- public List<CatchBatchValidationError> validate(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
- List<CatchBatchValidationError> errors = Lists.newArrayList();
- validate(catchBatch.getChildBatchs(), errors, 1);
- return errors;
- }
-
- @Override
- public CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) {
- Preconditions.checkNotNull(fishingOperationId);
-
- Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
-
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch source;
- try {
- source = catchBatchDao.loadFullTree(catchBatchId, true, true);
- } catch (CatchBatchValidationException e) {
- throw new DataRetrievalFailureException("Invalid batch tree structure, for fishing operation id=" + fishingOperationId, e);
- }
-
- CatchBatch result = new CatchBatch();
- result.setId(source.getId().toString());
- result.setCatchTotalWeight(source.getWeight());
-
- // Vrac
- SortingBatch vracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID);
- result.setCatchTotalSortedCarousselWeight(vracBatch.getWeight());
- result.setCatchTotalSortedTremisWeight(vracBatch.getWeightBeforeSampling());
- {
- // Species
- SortingBatch speciesBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
-
- result.setSpeciesTotalSampleSortedWeight(speciesBatch.getWeight());
- result.setSpeciesTotalSortedWeight(speciesBatch.getWeightBeforeSampling());
-
- {
- // Inert
- SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
- "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
- result.setSpeciesTotalInertWeight(inertBatch.getWeight());
-
- // Alive no itemized
- SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
- "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
- result.setSpeciesTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight());
- }
-
- // TODO : Benthos, Plancton...
- }
-
- // Hors Vrac
- SortingBatch horsVracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID);
- result.setCatchTotalUnsortedWeight(horsVracBatch.getWeight());
- {
- // Species
- SortingBatch speciesBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
-
- result.setSpeciesTotalUnsortedWeight(speciesBatch.getWeight());
-
- // TODO : Benthos, Plancton...
- }
-
- // Non trié
- SortingBatch unsortedBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID);
- result.setCatchTotalRejectedWeight(unsortedBatch.getWeight());
-
- return result;
- }
-
- @Override
-
- public CatchBatch createCatchBatch(CatchBatch bean) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkArgument(bean.getId() == null);
- Preconditions.checkNotNull(bean.getFishingOperation());
- Preconditions.checkNotNull(bean.getFishingOperation().getId());
-
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = fr.ifremer.adagio.core.dao.data.batch.CatchBatch.Factory.newInstance();
- beanToEntity(bean, catchBatch, true);
- catchBatch = catchBatchDao.create(catchBatch);
- bean.setId(String.valueOf(catchBatch.getId()));
-
- // Link to fishing operation
- getCurrentSession().flush();
- Integer fishingOperationId = Integer.valueOf(bean.getFishingOperation().getId());
- int rowUpdated = queryUpdate("updateFishingOperationCatchBatch",
- "fishingOperationId", IntegerType.INSTANCE, fishingOperationId,
- "catchBatchId", IntegerType.INSTANCE, catchBatch.getId());
- if (rowUpdated == 0) {
- throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found.");
- }
-
- return bean;
- }
-
- @Override
- @CacheEvict(value = "batchTree", key="#bean.fishingOperation.id")
- public CatchBatch saveCatchBatch(CatchBatch bean) {
-
- Preconditions.checkNotNull(bean);
- Preconditions.checkNotNull(bean.getId());
-
- getCurrentSession().enableFetchProfile("batch-with-childs");
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(Integer.valueOf(bean.getId()));
- if (catchBatch == null) {
- throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId());
- }
-
- beanToEntity(bean, catchBatch, true);
- catchBatchDao.update(catchBatch);
- getCurrentSession().flush();
-
- return bean;
- }
-
- @Override
- public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) {
-
- // Load batch tree
- Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- List<SpeciesBatch> result = new ArrayList<SpeciesBatch>();
-
- // Vrac / Species
- SortingBatch vracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- for (Iterator<Batch> iterator = vracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch source = (SortingBatch) iterator.next();
-
- // evict some special batches : Life (or Biota) and Inert
- if (source.getReferenceTaxon() != null
- && enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) == false
- && enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId()) == false) {
- SpeciesBatch target = new SpeciesBatch();
-
- entityToBean(source, target);
- result.add(target);
- }
- }
-
- // Hors-Vrac / Species
- SortingBatch horsVracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- for (Iterator<Batch> iterator = horsVracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch source = (SortingBatch) iterator.next();
-
- SpeciesBatch target = new SpeciesBatch();
-
- entityToBean(source, target);
- result.add(target);
- }
-
- return result;
- }
-
- protected SpeciesBatch entityToBean(SortingBatch source, SpeciesBatch target) {
-
- target.setId(source.getId().toString());
-
- // Individual count
- target.setNumber(source.getIndividualCount());
-
- // Convert database weight (and sampling ratio) into UI weight and sampleCategoryWeight
- if (source.getWeight() != null && source.getWeightBeforeSampling() == null) {
- target.setSampleCategoryWeight(source.getWeight());
- }
- else {
- target.setWeight(source.getWeight());
- target.setSampleCategoryWeight(source.getWeightBeforeSampling());
- }
-
- // Comments
- target.setComment(source.getComments());
-
- // Sample category type (only one is applied)
- SortingMeasurement sm = null;
- if (source.getSortingMeasurements().size() == 1) {
- sm = source.getSortingMeasurements().iterator().next();
- }
- else if (source.getReferenceTaxon() != null && source.getReferenceTaxon().getId() != null){
- sm = measurementHelper.getInheritedSortingMeasurement(source, enumeration.PMFM_ID_SORTED_UNSORTED);
- }
- if (sm != null) {
- SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(sm.getPmfm().getId());
- if (sampleCategory != null) {
- setSampleCategoryQualitative(target, sm.getPmfm().getId(), sm.getNumericalValue(), sm.getAlphanumericalValue(), sm.getQualitativeValue().getId());
- }
- }
-
- // Species
- Integer referenceTaxonId = source.getInheritedReferenceTaxonId();
- if (referenceTaxonId == null && source.getReferenceTaxon() != null) {
- referenceTaxonId = source.getReferenceTaxon().getId();
- }
- if (referenceTaxonId != null) {
- // TODO : add cache on getSpeciesByReferenceTaxonId
- Species species = referentialService.getSpeciesByReferenceTaxonId(referenceTaxonId);
- target.setSpecies(species);
- }
-
- if (target.getSampleCategoryType() != null && source.getChildBatchs().size() > 0) {
- List<SpeciesBatch> targetChilds = Lists.newArrayList();
- for (Iterator<Batch> iterator = source.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch sourceChild = (SortingBatch) iterator.next();
- SpeciesBatch targetChild = new SpeciesBatch();
- entityToBean(sourceChild, targetChild);
- if (targetChild.getSampleCategoryValue() != null) {
- targetChilds.add(targetChild);
- targetChild.setParentBatch(target);
- }
- }
- target.setChildBatchs(targetChilds);
- }
-
- return target;
- }
-
- @Override
- public SpeciesBatch createSpeciesBatch(SpeciesBatch bean,
- String parentBatchId) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkArgument(bean.getId() == null);
- Preconditions.checkNotNull(bean.getSpecies());
- Preconditions.checkNotNull(bean.getSpecies().getId());
- Preconditions.checkNotNull(bean.getFishingOperation());
- Preconditions.checkNotNull(bean.getFishingOperation().getId());
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- // Load full batch tree
- Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(bean.getFishingOperation().getId()));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- SortingBatch batch = SortingBatch.Factory.newInstance();
- beanToEntity(bean, batch, parentBatchId, catchBatch, true);
- batch = sortingBatchDao.create(batch);
-
- bean.setId(String.valueOf(batch.getId()));
-
- getCurrentSession().flush();
-
- return bean;
- }
-
- @Override
- public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkNotNull(bean.getId());
-
- // Load full batch tree
- Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(bean.getId()));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- SortingBatch batch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(bean.getId()));
- String parentBatchId = null;
- if (bean.getParentBatch() != null) {
- parentBatchId = bean.getParentBatch().getId();
- }
- beanToEntity(bean, batch, parentBatchId, catchBatch, true);
- sortingBatchDao.update(batch);
- getCurrentSession().flush();
-
- return bean;
- }
-
- @Override
- public void deleteSpeciesBatch(String id) {
- Preconditions.checkNotNull(id);
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- catchBatchDao.removeWithChildren(Integer.valueOf(id));
-
- getCurrentSession().flush();
- }
-
- public void deleteSpeciesSubBatch(String id) {
- deleteSpeciesBatch(id);
- }
-
- public void changeSpeciesBatchSpecies(String batchId, Species species) {
- Preconditions.checkNotNull(batchId);
- Preconditions.checkNotNull(species);
- Preconditions.checkNotNull(species.getReferenceTaxonId());
-
- if (log.isDebugEnabled()) {
- log.debug("Changing species for batch id=" + batchId);
- }
-
- int rowUpdated = queryUpdate("updateBatchSpecies",
- "batchId", IntegerType.INSTANCE, Integer.valueOf(batchId),
- "referenceTaxonId", IntegerType.INSTANCE, species.getReferenceTaxonId());
- Preconditions.checkArgument(rowUpdated == 1, "Unable to update operation, to be linked with catch batch.");
- }
-
- public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
- String speciesBatchId) {
- List<SpeciesBatchFrequency> results = Lists.newArrayList();
-
- Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- if (catchBatchId == null) {
- return results;
- }
-
- SortingBatch sortingBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
-
- for (Iterator<Batch> iterator = sortingBatch.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch source = (SortingBatch) iterator.next();
- SpeciesBatchFrequency target = new SpeciesBatchFrequency();
-
- entityToBean(source, target);
- results.add(target);
- }
- return results;
- }
-
- protected void entityToBean(SortingBatch source, SpeciesBatchFrequency target) {
-
- target.setId(source.getId().toString());
-
- target.setNumber(source.getIndividualCount());
- target.setWeight(source.getWeight());
- target.setComment(source.getComments());
-
- // Length step category
- if (source.getSortingMeasurements().size() == 1) {
- SortingMeasurement sm = source.getSortingMeasurements().iterator().next();
- if (sm.getPmfm() != null && sm.getPmfm().getId() != null) {
- Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(sm.getPmfm().getId());
- target.setLengthStepCaracteristic(lengthStepCaracteristic);
- }
-
- // Length
- target.setLengthStep(sm.getNumericalValue());
- }
- }
-
- public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(
- String speciesBatchId, List<SpeciesBatchFrequency> frequencies) {
- Preconditions.checkNotNull(speciesBatchId);
- Preconditions.checkNotNull(frequencies);
-
- if (frequencies.size() == 0) {
- return frequencies;
- }
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- if (catchBatch == null) {
- return frequencies;
- }
-
- // Retrieve parent
- SortingBatch parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
-
- // Remember child ids, to remove unchanged item (see at bottom in this method)
- List<Integer> notUpdatedChildIds = Lists.newArrayList();
- for (Iterator<Batch> iterator = parentBatch.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch sortingBatch = (SortingBatch) iterator.next();
- notUpdatedChildIds.add(sortingBatch.getId());
- }
-
- short rankOrder = 0;
- String pmfmId = null;
- List<SortingBatch> batchsToUpdate = Lists.newArrayList();
- for (SpeciesBatchFrequency source : frequencies) {
- rankOrder++;
-
- // Check that all frequencies have the same length PMFM
- if (pmfmId == null) {
- source.getLengthStepCaracteristic().getId();
- } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) {
- throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic");
- }
-
- // Not existing batch
- SortingBatch target = null;
- if (source.getId() == null) {
- target = SortingBatch.Factory.newInstance();
-
- // Fill the sorting batch from the source
- beanToEntity(source, target, parentBatch, rankOrder, true);
-
- // Create the targeted batch, then update the source id
- sortingBatchDao.create(target);
- source.setId(target.getId().toString());
- }
-
- // Existing batch
- else {
- target = sortingBatchDao.load(Integer.valueOf(source.getId()));
-
- // Fill the sorting batch from the source
- beanToEntity(source, target, parentBatch, rankOrder, true);
-
- // Add the batch into a list (will be update later, using this list)
- batchsToUpdate.add(target);
-
- notUpdatedChildIds.remove(target.getId());
- }
- }
-
- // If some batchs need to be update, do it
- if (batchsToUpdate.size() > 0) {
- sortingBatchDao.update(batchsToUpdate);
- }
-
- if (notUpdatedChildIds.size() > 0) {
- for (Iterator<Integer> iterator = notUpdatedChildIds.iterator(); iterator.hasNext();) {
- Integer batchId = iterator.next();
- catchBatchDao.removeWithChildren(batchId);
- }
- }
-
- getCurrentSession().flush();
-
- return frequencies;
- }
-
- // ------------------------------------------------------------------------//
- // -- Internal methods --//
- // ------------------------------------------------------------------------//
-
- protected void validate(Collection<Batch> batchs, List<CatchBatchValidationError> errors, int treeLevel) {
-
- List<Integer> expectedPmfms = null;
- boolean expectedReferenceTaxon = false;
- // First tree level : should have pmfm SORTED (Vrac, Hors Vrac, Non trié)
- if (treeLevel == 1) {
- expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTED_UNSORTED);
- }
- // Second tree level : should have pmfm SORTING_TYPE (Species, Benthos...)
- else if (treeLevel == 2) {
- expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTING_TYPE);
- }
- else if (treeLevel == 3) {
- expectedReferenceTaxon = true;
- }
- else if (treeLevel > 3) {
- expectedPmfms = referentialService.getSampleCategoryIds();
- expectedPmfms.remove(enumeration.PMFM_ID_SORTED_UNSORTED);
- }
-
- // First level : should be only PMFM=SORTED
- for (Iterator<Batch> iterator = batchs.iterator(); iterator.hasNext();) {
- SortingBatch batch = (SortingBatch) iterator.next();
- boolean batchHasError = false;
-
- // For all sorting measurements
- if (batch.getSortingMeasurements() != null && batch.getSortingMeasurements().size() > 0) {
- for (Iterator<SortingMeasurement> iterator2 = batch.getSortingMeasurements().iterator(); iterator2.hasNext();) {
- SortingMeasurement sm = iterator2.next();
- Integer pmfmId = sm.getPmfm().getId();
- if (expectedReferenceTaxon) {
- CatchBatchValidationError error = new CatchBatchValidationError(
- "tutti.persistence.batch.validation.onlyTaxonButPmfmFound",
- _("tutti.persistence.batch.validation.onlyTaxonButPmfmFound", batch.getId(), pmfmId),
- CatchBatchValidationError.GRAVITY_ERROR);
- errors.add(error);
- }
- else if (expectedPmfms.contains(pmfmId) == false) {
- if (sm.getNumericalValue() == null || batch.getChildBatchs().size() > 0) {
- batchHasError = true;
- CatchBatchValidationError error = new CatchBatchValidationError(
- "tutti.persistence.batch.validation.pmfmNotFound",
- _("tutti.persistence.batch.validation.pmfmNotFound",
- batch.getId(), Arrays.toString(expectedPmfms.toArray()), pmfmId),
- CatchBatchValidationError.GRAVITY_ERROR);
- errors.add(error);
- }
- }
- }
- }
- else if (expectedPmfms != null && expectedPmfms.size() > 0){
- batchHasError = true;
- CatchBatchValidationError error = new CatchBatchValidationError(
- "tutti.persistence.batch.validation.pmfmNotFound",
- _("tutti.persistence.batch.validation.pmfmNotFound",
- batch.getId(), Arrays.toString(expectedPmfms.toArray()), "null"),
- CatchBatchValidationError.GRAVITY_ERROR);
- errors.add(error);
- }
-
- if (!batchHasError && expectedReferenceTaxon == true && batch.getReferenceTaxon() == null) {
- CatchBatchValidationError error = new CatchBatchValidationError(
- "tutti.persistence.batch.validation.referenceTaxonNotFound",
- _("tutti.persistence.batch.validation.referenceTaxonNotFound", batch.getId()),
- CatchBatchValidationError.GRAVITY_ERROR);
- errors.add(error);
- }
-
- if (!batchHasError) {
- validate(batch.getChildBatchs(), errors, treeLevel+1);
- }
- }
- }
-
- protected void beanToEntity(SpeciesBatch source,
- SortingBatch target,
- String parentBatchId,
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch,
- boolean copyIfNull) {
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve recorder department
- Integer recorderDepartmentId = getRecorderDepartmentId();
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // If parent and root need to be set
- if (target.getId() == null
- || target.getRootBatch() == null
- || (target.getParentBatch() != null && !target.getParentBatch().getId().toString().equals(parentBatchId))) {
- setBatchParents(source, target, parentBatchId, catchBatch);
- }
-
- // RankOrder (initialize once, at creation)
- if (target.getRankOrder() == null) {
- // Start rank order at 3, because of special batches 'Biota' and 'Inert'
- short rankOrder = (short) 3;
- if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) {
- // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?)
- rankOrder += (short) source.getParentBatch().getChildBatchs().size();
- }
- target.setRankOrder(rankOrder);
- }
-
- // Force subgroup count to '1', as Allegro
- target.setSubgroupCount(1f);
-
- // Weight or SampleCategoryWeight
- if (copyIfNull && source.getWeight() == null && source.getSampleCategoryWeight() == null) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getSampleCategoryWeight() != null && source.getWeight() == null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sampling Ratio
- if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) {
- String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight();
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight());
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sorting measurement
- if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) {
- Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
- // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch)
- if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
- SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId,
- source.getSampleCategoryType(), source.getSampleCategoryValue());
- notChangedSortingMeasurements.remove(sortingMeasurement);
- }
- }
-
- // Individual count
- if (copyIfNull && source.getNumber() == null) {
- target.setIndividualCount(null);
- } else if (source.getNumber() != null) {
- target.setIndividualCount(source.getNumber());
- }
-
- // Species
- if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) {
- target.setReferenceTaxon(null);
- } else if (source.getSpecies() != null && parentBatchId == null) {
- ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId());
- target.setReferenceTaxon(referenceTaxon);
- }
-
- // QualityFlag
- if (source.isSpeciesToConfirm()) {
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL));
- } else {
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- }
-
- // Comments
- if (copyIfNull && source.getComment() == null) {
- target.setComments(null);
- } else if (source.getComment() != null) {
- target.setComments(source.getComment());
- }
-
- // Exhaustive inventory (always true under a species batch)
- target.setExhaustiveInventory(true);
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- public void setBatchParents(SpeciesBatch source, SortingBatch target, String parentBatchIdStr,
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
-
- Preconditions.checkNotNull(target);
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Load existing parent and root
- SortingBatch parentBatch = null;
- if (parentBatchIdStr != null) {
- parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(parentBatchIdStr));
- }
-
- // Or retrieve parent batch, from pmfm id
- else {
- // Retrieve category type
- Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
- if (pmfmId == null || !pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
- throw new DataIntegrityViolationException(MessageFormat.format(
- "A species batch with no parent should have a sampleCategoryType {0} (PMFM.ID={1})",
- SampleCategoryEnum.sortedUnsorted.name(),
- enumeration.PMFM_ID_SORTED_UNSORTED));
- }
- Integer qualitativeValueId = convertSampleCategoryValueIntoQualitativeId(source.getSampleCategoryValue());
-
- parentBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
- "pmfmId", pmfmId, qualitativeValueId,
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
-
- // Parent Batch
- target.setParentBatch(parentBatch);
- }
-
-
- if (parentBatch == null) {
- throw new DataIntegrityViolationException(
- "Could not retrieve parent batch, for a given speciesBatch : invalid batch tree structure. Please make sure CatchBatch has been saved before to create a SpeciesBatch.");
- }
-
- // Parent Batch
- target.setParentBatch(parentBatch);
- target.setRootBatch(catchBatch);
- }
-
- Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) {
- if (value == null)
- return null;
- Integer qualitativeValueId = null;
- if (value instanceof CaracteristicQualitativeValue) {
- CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value;
- qualitativeValueId = Integer.valueOf(cqValue.getId());
- } else if (value instanceof String) {
- qualitativeValueId = Integer.valueOf((String) value);
- }
- return qualitativeValueId;
- }
-
- protected void setSampleCategoryQualitative(SpeciesBatch target, Integer pmfmId, Float numericalvalue, String alphanumericalValue,
- Integer qualitativeValueId) {
- // skip if null or corresponding to the SORTING_TYPE PMFM (Expèce, Benthos, Plancton, etc.)
- if (pmfmId == null || pmfmId.equals(enumeration.PMFM_ID_SORTING_TYPE)) {
- return;
- }
-
- SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
- Preconditions.checkNotNull(sampleCategory, "Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId);
-
- target.setSampleCategoryType(sampleCategory);
- if (numericalvalue != null) {
- target.setSampleCategoryValue(numericalvalue);
- return;
- }
- if (alphanumericalValue != null) {
- target.setSampleCategoryValue(alphanumericalValue);
- return;
- }
-
- Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId);
- if (caracteristic == null || caracteristic.getCaracteristicType() != CaracteristicType.QUALITATIVE) {
- return;
- }
- CaracteristicQualitativeValue value = null;
- for (CaracteristicQualitativeValue qv : caracteristic.getQualitativeValue()) {
- if (qualitativeValueId == Integer.parseInt(qv.getId())) {
- value = qv;
- break;
- }
- }
- target.setSampleCategoryValue(value);
- }
-
- protected void beanToEntity(SpeciesBatchFrequency source, SortingBatch target, SortingBatch parentBatch, short rankOrder, boolean copyIfNull) {
- Preconditions.checkNotNull(source.getBatch());
- Preconditions.checkNotNull(source.getBatch().getId());
-
- // Retrieve recorder department
- Integer recorderDepartmentId = getRecorderDepartmentId();
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // If parent and root need to be set
- if (target.getId() == null
- || target.getRootBatch() == null
- || (target.getParentBatch() != null && !target.getParentBatch().getId().equals(parentBatch.getId()))) {
-
- target.setParentBatch(parentBatch);
- target.setRootBatch(parentBatch.getRootBatch());
- }
-
- // RankOrder
- target.setRankOrder(rankOrder);
-
- // Weight or SampleCategoryWeight
- if (copyIfNull && source.getWeight() == null) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getWeight() != null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sorting measurement
- if (copyIfNull && (source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getLengthStepCaracteristic() != null && source.getLengthStep() != null) {
- Integer pmfmId = Integer.valueOf(source.getLengthStepCaracteristic().getId());
- SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, pmfmId,
- source.getLengthStep());
- notChangedSortingMeasurements.remove(sortingMeasurement);
- }
-
- // Individual count
- if (copyIfNull && source.getNumber() == null) {
- target.setIndividualCount(null);
- } else if (source.getNumber() != null) {
- target.setIndividualCount(source.getNumber());
- }
-
- // Species
- target.setReferenceTaxon(null);
-
- // QualityFlag
- target.setQualityFlag(parentBatch.getQualityFlag());
-
- // Comments
- if (copyIfNull && source.getComment() == null) {
- target.setComments(null);
- } else if (source.getComment() != null) {
- target.setComments(source.getComment());
- }
-
- // Exhaustive inventory (always true under a species batch)
- target.setExhaustiveInventory(true);
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- protected UIWeight convertDatabase2UI(Float weight, Float samplingRatio, String samplingRatioText) {
- UIWeight result = new UIWeight();
-
- // Weight & sampleCategory Weight
- if (samplingRatio == null) {
- result.sampleCategoryWeight = weight;
- } else if (weight != null) {
- String startStr = weight.toString().replace(',', '.') + "/";
- if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
- String weightStr = samplingRatioText.substring(startStr.length());
- if (weightStr != null && !weightStr.isEmpty()) {
- result.sampleCategoryWeight = Float.parseFloat(weightStr);
- result.weight = weight;
- }
- } else {
- result.sampleCategoryWeight = weight;
- }
- }
- return result;
- }
-
- static class UIWeight {
- Float sampleCategoryWeight = null;
-
- Float weight = null;
- }
-
- protected void beanToEntity(CatchBatch source,
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch target,
- boolean copyIfNull) {
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve recorder department
- Integer recorderDepartmentId = getRecorderDepartmentId();
-
- // First initialization (when created)
- Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId());
- target.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId));
-
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRankOrder((short) 1);
- target.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue());
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
-
- // Total Weight
- if (copyIfNull && source.getCatchTotalWeight() == null) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (source.getCatchTotalWeight() != null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getCatchTotalWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- Map<Integer, SortingBatch> catchBatchChilds = getChildsMap(target, enumeration.PMFM_ID_SORTED_UNSORTED);
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac
- // -----------------------------------------------------------------------------
- {
- SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_VRAC_ID);
- if (batch == null) {
- batch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(batch);
- }
- beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
- source.getCatchTotalSortedCarousselWeight(), source.getCatchTotalSortedTremisWeight(),
- copyIfNull);
- batch.setRankOrder((short) 1);
-
- // Manage childs :
- {
- Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac / Species
- // -----------------------------------------------------------------------------
- SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- if (speciesBatch == null) {
- speciesBatch = SortingBatch.Factory.newInstance();
- if (batch.getChildBatchs() == null) {
- batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
- } else {
- batch.getChildBatchs().add(speciesBatch);
- }
- }
- beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
- source.getSpeciesTotalSampleSortedWeight(), source.getSpeciesTotalSortedWeight(),
- copyIfNull);
- speciesBatch.setRankOrder((short) 1);
-
- {
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac / Species / Alive not itemized
- // -----------------------------------------------------------------------------
- SortingBatch aliveNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
- if (aliveNotItemizedBatch == null) {
- aliveNotItemizedBatch = SortingBatch.Factory.newInstance();
- if (speciesBatch.getChildBatchs() == null) {
- speciesBatch.setChildBatchs(Lists.newArrayList((Batch) aliveNotItemizedBatch));
- } else {
- speciesBatch.getChildBatchs().add(aliveNotItemizedBatch);
- }
- }
- beanToEntityReferenceTaxonBatch(target, speciesBatch, aliveNotItemizedBatch, recorderDepartmentId,
- enumeration.REFERENCE_TAXON_ID_LIFE,
- source.getSpeciesTotalLivingNotItemizedWeight(), null,
- copyIfNull);
- aliveNotItemizedBatch.setRankOrder((short) 1);
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac / Species / Inert (not alive)
- // -----------------------------------------------------------------------------
- SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
- if (inertBatch == null) {
- inertBatch = SortingBatch.Factory.newInstance();
- speciesBatch.getChildBatchs().add(inertBatch);
- }
- beanToEntityReferenceTaxonBatch(target, speciesBatch, inertBatch, recorderDepartmentId,
- enumeration.REFERENCE_TAXON_ID_INERT,
- source.getSpeciesTotalInertWeight(), null,
- copyIfNull);
- inertBatch.setRankOrder((short) 2);
- }
- }
- // TODO BL : benthos, plancton, macro déchet...
- }
-
- // -----------------------------------------------------------------------------
- // Sorted Hors Vrac
- // -----------------------------------------------------------------------------
- {
- SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_HORS_VRAC_ID);
- if (batch == null) {
- batch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(batch);
- }
- beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
- source.getCatchTotalUnsortedWeight(), null,
- copyIfNull);
- batch.setRankOrder((short) 2);
-
- // Manage childs :
- {
- Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
-
- // Species :
- SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- if (speciesBatch == null) {
- speciesBatch = SortingBatch.Factory.newInstance();
- if (batch.getChildBatchs() == null) {
- batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
- } else {
- batch.getChildBatchs().add(speciesBatch);
- }
- }
- beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
- source.getSpeciesTotalUnsortedWeight(), null,
- copyIfNull);
- speciesBatch.setRankOrder((short) 1);
- }
-
- // TODO BL : benthos, plancton, macro déchet...
- }
-
- // -----------------------------------------------------------------------------
- // Unsorted (=rejected)
- // -----------------------------------------------------------------------------
- // Unsorted :
- SortingBatch unsortedBatch = catchBatchChilds.get(enumeration.QUALITATIVE_UNSORTED_ID);
- if (unsortedBatch == null) {
- unsortedBatch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(unsortedBatch);
- }
- beanToEntitySortingBatch(target, target, unsortedBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID,
- source.getCatchTotalRejectedWeight(), null,
- copyIfNull);
- unsortedBatch.setRankOrder((short) 3);
-
- }
-
- protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) {
- Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
- if (parentBatch.getChildBatchs() == null) {
- return batchByQualitativeValueId;
- }
- for (Batch childBatch : parentBatch.getChildBatchs()) {
- SortingBatch childSortingBatch = (SortingBatch) childBatch;
- SortingMeasurement sm = measurementHelper.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false);
- if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) {
- batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), childSortingBatch);
- }
- }
- return batchByQualitativeValueId;
- }
-
- /**
- * Retrieve child batchs if species is "Life" or "No life"
- * (need to retrieve: speciesTotalLivingNotItemizedWeight and speciesTotalInertWeight)
- *
- * @param parentBatch
- * @return
- */
- protected Map<Integer, SortingBatch> getChildAliveNotSortedOrInert(Batch parentBatch) {
- Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
- if (parentBatch.getChildBatchs() == null) {
- return batchByQualitativeValueId;
- }
- for (Batch childBatch : parentBatch.getChildBatchs()) {
- SortingBatch childSortingBatch = (SortingBatch) childBatch;
- if (childSortingBatch.getReferenceTaxon() != null && childSortingBatch.getId().intValue() < 0) {
- if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
- batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
- } else if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
- batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
- }
- }
- }
- return batchByQualitativeValueId;
- }
-
- protected void beanToEntitySortingBatch(
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
- fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
- fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
- Integer recorderDepartmentId,
- Integer sortingPmfmId,
- Integer sortingQualitativeValueId,
- Float weight,
- Float sampleWeight,
- boolean copyIfNull) {
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // Some mandatory properties :
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRootBatch(rootBatch);
- target.setParentBatch(parentBatch);
- target.setExhaustiveInventory(true);
-
- // No taxon or taxon group
- target.setReferenceTaxon(null);
- target.setTaxonGroup(null);
-
- // Sorting measurement
- if (copyIfNull && (sortingPmfmId == null || sortingQualitativeValueId == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (sortingPmfmId != null && sortingQualitativeValueId != null) {
- SortingMeasurement sm = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId);
- notChangedSortingMeasurements.remove(sm);
- }
-
- // Sampling Ratio
- if (copyIfNull && (sampleWeight == null || weight == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (sampleWeight != null && weight != null) {
- String samplingRatioText = weight + "/" + sampleWeight;
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(weight / sampleWeight);
- }
-
- // Weight
- if (copyIfNull && (sampleWeight == null && weight == null)) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (sampleWeight != null || weight != null) {
- Float batchReferenceWeight = weight;
- if (batchReferenceWeight == null) {
- batchReferenceWeight = sampleWeight;
- }
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- protected void beanToEntityReferenceTaxonBatch(
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
- fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
- fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
- Integer recorderDepartmentId,
- Integer referenceTaxonId,
- Float weight,
- Float sampleWeight,
- boolean copyIfNull) {
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // Some mandatory properties :
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRootBatch(rootBatch);
- target.setParentBatch(parentBatch);
- target.setExhaustiveInventory(true);
-
- // Reference taxon
- target.setReferenceTaxon(load(ReferenceTaxonImpl.class, referenceTaxonId));
- target.setTaxonGroup(null);
-
- // Sampling Ratio
- if (copyIfNull && (sampleWeight == null || weight == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (sampleWeight != null && weight != null) {
- String samplingRatioText = weight + "/" + sampleWeight;
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(weight / sampleWeight);
- }
-
- // Weight
- if (copyIfNull && (sampleWeight == null && weight == null)) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (sampleWeight != null || weight != null) {
- Float batchReferenceWeight = weight;
- if (batchReferenceWeight == null) {
- batchReferenceWeight = sampleWeight;
- }
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- protected Integer getRecorderDepartmentId() {
- // TODO BL : voir si on peut récupérer le departement (du 1er saisisseur ?)
- return enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
- }
-}
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.Serializable;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.annotation.Resource;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.FlushMode;
+import org.hibernate.type.IntegerType;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.DataRetrievalFailureException;
+import org.springframework.stereotype.Service;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+import fr.ifremer.adagio.core.dao.data.batch.Batch;
+import fr.ifremer.adagio.core.dao.data.batch.CatchBatchExtendDao;
+import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
+import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
+import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationError;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidator;
+import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
+import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
+import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
+import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
+import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
+import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
+import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
+import fr.ifremer.tutti.persistence.entities.referential.Species;
+import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
+
+@Service("batchPersistenceService")
+public class BatchPersistenceServiceImpl
+ extends AbstractPersistenceService implements BatchPersistenceService, CatchBatchValidator
+ {
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(BatchPersistenceServiceImpl.class);
+
+ @Resource(name = "referentialPersistenceService")
+ protected ReferentialPersistenceService referentialService;
+
+ @Resource(name = "denormalizedBatchDao")
+ protected DenormalizedBatchDao denormalizedBatchDao;
+
+ @Resource(name = "sortingBatchDao")
+ protected SortingBatchDao sortingBatchDao;
+
+ @Resource(name = "catchBatchDao")
+ protected CatchBatchExtendDao catchBatchDao;
+
+ @Resource(name = "measurementPersistenceHelper")
+ protected MeasurementPersistenceHelper measurementHelper;
+
+ @Override
+ public void init() {
+ super.init();
+ catchBatchDao.registerCatchBatchValidator(this);
+ }
+
+ @Override
+ public void close() {
+ catchBatchDao.unregisterCatchBatchValidator(this);
+ super.close();
+ }
+
+ @Override
+ public boolean isEnable(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+ // Apply validation only on catch batch for fishingOperation
+ return (catchBatch.getFishingOperation() != null);
+ }
+
+ @Override
+ public List<CatchBatchValidationError> validate(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+ List<CatchBatchValidationError> errors = Lists.newArrayList();
+ validate(catchBatch.getChildBatchs(), errors, 1);
+ return errors;
+ }
+
+ @Override
+ public CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) {
+ Preconditions.checkNotNull(fishingOperationId);
+
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
+
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch source;
+ try {
+ source = catchBatchDao.loadFullTree(catchBatchId, true, true);
+ } catch (CatchBatchValidationException e) {
+ throw new DataRetrievalFailureException("Invalid batch tree structure, for fishing operation id=" + fishingOperationId, e);
+ }
+
+ CatchBatch result = new CatchBatch();
+ result.setId(source.getId().toString());
+ result.setCatchTotalWeight(source.getWeight());
+
+ // Vrac
+ SortingBatch vracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID);
+ result.setCatchTotalSortedCarousselWeight(vracBatch.getWeight());
+ result.setCatchTotalSortedTremisWeight(vracBatch.getWeightBeforeSampling());
+ {
+ // Species
+ SortingBatch speciesBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ result.setSpeciesTotalSampleSortedWeight(speciesBatch.getWeight());
+ result.setSpeciesTotalSortedWeight(speciesBatch.getWeightBeforeSampling());
+
+ {
+ // Inert
+ SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
+ "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
+ result.setSpeciesTotalInertWeight(inertBatch.getWeight());
+
+ // Alive no itemized
+ SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
+ "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
+ result.setSpeciesTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight());
+ }
+
+ // TODO : Benthos, Plancton...
+ }
+
+ // Hors Vrac
+ SortingBatch horsVracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID);
+ result.setCatchTotalUnsortedWeight(horsVracBatch.getWeight());
+ {
+ // Species
+ SortingBatch speciesBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ result.setSpeciesTotalUnsortedWeight(speciesBatch.getWeight());
+
+ // TODO : Benthos, Plancton...
+ }
+
+ // Non trié
+ SortingBatch unsortedBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID);
+ result.setCatchTotalRejectedWeight(unsortedBatch.getWeight());
+
+ return result;
+ }
+
+ @Override
+
+ public CatchBatch createCatchBatch(CatchBatch bean) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkArgument(bean.getId() == null);
+ Preconditions.checkNotNull(bean.getFishingOperation());
+ Preconditions.checkNotNull(bean.getFishingOperation().getId());
+
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = fr.ifremer.adagio.core.dao.data.batch.CatchBatch.Factory.newInstance();
+ beanToEntity(bean, catchBatch, true);
+ catchBatch = catchBatchDao.create(catchBatch);
+ bean.setId(String.valueOf(catchBatch.getId()));
+
+ // Link to fishing operation
+ getCurrentSession().flush();
+ Integer fishingOperationId = Integer.valueOf(bean.getFishingOperation().getId());
+ int rowUpdated = queryUpdate("updateFishingOperationCatchBatch",
+ "fishingOperationId", IntegerType.INSTANCE, fishingOperationId,
+ "catchBatchId", IntegerType.INSTANCE, catchBatch.getId());
+ if (rowUpdated == 0) {
+ throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found.");
+ }
+
+ return bean;
+ }
+
+ @Override
+ @CacheEvict(value = "batchTree", key="#bean.fishingOperation.id")
+ public CatchBatch saveCatchBatch(CatchBatch bean) {
+
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkNotNull(bean.getId());
+
+ getCurrentSession().enableFetchProfile("batch-with-childs");
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(Integer.valueOf(bean.getId()));
+ if (catchBatch == null) {
+ throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId());
+ }
+
+ beanToEntity(bean, catchBatch, true);
+ catchBatchDao.update(catchBatch);
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) {
+
+ // Load batch tree
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ List<SpeciesBatch> result = new ArrayList<SpeciesBatch>();
+
+ // Vrac / Species
+ SortingBatch vracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ for (Iterator<Batch> iterator = vracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+
+ // evict some special batches : Life (or Biota) and Inert
+ if (source.getReferenceTaxon() != null
+ && enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) == false
+ && enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId()) == false) {
+ SpeciesBatch target = new SpeciesBatch();
+
+ entityToBean(source, target);
+ result.add(target);
+ }
+ }
+
+ // Hors-Vrac / Species
+ SortingBatch horsVracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ for (Iterator<Batch> iterator = horsVracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+
+ SpeciesBatch target = new SpeciesBatch();
+
+ entityToBean(source, target);
+ result.add(target);
+ }
+
+ return result;
+ }
+
+ protected SpeciesBatch entityToBean(SortingBatch source, SpeciesBatch target) {
+
+ target.setId(source.getId().toString());
+
+ // Individual count
+ target.setNumber(source.getIndividualCount());
+
+ // Convert database weight (and sampling ratio) into UI weight and sampleCategoryWeight
+ if (source.getWeight() != null && source.getWeightBeforeSampling() == null) {
+ target.setSampleCategoryWeight(source.getWeight());
+ }
+ else {
+ target.setWeight(source.getWeight());
+ target.setSampleCategoryWeight(source.getWeightBeforeSampling());
+ }
+
+ // Comments
+ target.setComment(source.getComments());
+
+ // Sample category type (only one is applied)
+ SortingMeasurement sm = null;
+ if (source.getSortingMeasurements().size() == 1) {
+ sm = source.getSortingMeasurements().iterator().next();
+ }
+ else if (source.getReferenceTaxon() != null && source.getReferenceTaxon().getId() != null){
+ sm = measurementHelper.getInheritedSortingMeasurement(source, enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+ if (sm != null) {
+ SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(sm.getPmfm().getId());
+ if (sampleCategory != null) {
+ setSampleCategoryQualitative(target, sm.getPmfm().getId(), sm.getNumericalValue(), sm.getAlphanumericalValue(), sm.getQualitativeValue().getId());
+ }
+ }
+
+ // Species
+ Integer referenceTaxonId = source.getInheritedReferenceTaxonId();
+ if (referenceTaxonId == null && source.getReferenceTaxon() != null) {
+ referenceTaxonId = source.getReferenceTaxon().getId();
+ }
+ if (referenceTaxonId != null) {
+ // TODO : add cache on getSpeciesByReferenceTaxonId
+ Species species = referentialService.getSpeciesByReferenceTaxonId(referenceTaxonId);
+ target.setSpecies(species);
+ }
+
+ if (target.getSampleCategoryType() != null && source.getChildBatchs().size() > 0) {
+ List<SpeciesBatch> targetChilds = Lists.newArrayList();
+ for (Iterator<Batch> iterator = source.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch sourceChild = (SortingBatch) iterator.next();
+ SpeciesBatch targetChild = new SpeciesBatch();
+ entityToBean(sourceChild, targetChild);
+ if (targetChild.getSampleCategoryValue() != null) {
+ targetChilds.add(targetChild);
+ targetChild.setParentBatch(target);
+ }
+ }
+ target.setChildBatchs(targetChilds);
+ }
+
+ return target;
+ }
+
+ @Override
+ public SpeciesBatch createSpeciesBatch(SpeciesBatch bean,
+ String parentBatchId) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkArgument(bean.getId() == null);
+ Preconditions.checkNotNull(bean.getSpecies());
+ Preconditions.checkNotNull(bean.getSpecies().getId());
+ Preconditions.checkNotNull(bean.getFishingOperation());
+ Preconditions.checkNotNull(bean.getFishingOperation().getId());
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ // Load full batch tree
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(bean.getFishingOperation().getId()));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ SortingBatch batch = SortingBatch.Factory.newInstance();
+ beanToEntity(bean, batch, parentBatchId, catchBatch, true);
+ batch = sortingBatchDao.create(batch);
+
+ bean.setId(String.valueOf(batch.getId()));
+
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkNotNull(bean.getId());
+
+ // Load full batch tree
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(bean.getId()));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ SortingBatch batch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(bean.getId()));
+ String parentBatchId = null;
+ if (bean.getParentBatch() != null) {
+ parentBatchId = bean.getParentBatch().getId();
+ }
+ beanToEntity(bean, batch, parentBatchId, catchBatch, true);
+ sortingBatchDao.update(batch);
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public void deleteSpeciesBatch(String id) {
+ Preconditions.checkNotNull(id);
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ catchBatchDao.removeWithChildren(Integer.valueOf(id));
+
+ getCurrentSession().flush();
+ }
+
+ public void deleteSpeciesSubBatch(String id) {
+ deleteSpeciesBatch(id);
+ }
+
+ public void changeSpeciesBatchSpecies(String batchId, Species species) {
+ Preconditions.checkNotNull(batchId);
+ Preconditions.checkNotNull(species);
+ Preconditions.checkNotNull(species.getReferenceTaxonId());
+
+ if (log.isDebugEnabled()) {
+ log.debug("Changing species for batch id=" + batchId);
+ }
+
+ int rowUpdated = queryUpdate("updateBatchSpecies",
+ "batchId", IntegerType.INSTANCE, Integer.valueOf(batchId),
+ "referenceTaxonId", IntegerType.INSTANCE, species.getReferenceTaxonId());
+ Preconditions.checkArgument(rowUpdated == 1, "Unable to update operation, to be linked with catch batch.");
+ }
+
+ public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
+ String speciesBatchId) {
+ List<SpeciesBatchFrequency> results = Lists.newArrayList();
+
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ if (catchBatchId == null) {
+ return results;
+ }
+
+ SortingBatch sortingBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
+
+ for (Iterator<Batch> iterator = sortingBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+ SpeciesBatchFrequency target = new SpeciesBatchFrequency();
+
+ entityToBean(source, target);
+ results.add(target);
+ }
+ return results;
+ }
+
+ protected void entityToBean(SortingBatch source, SpeciesBatchFrequency target) {
+
+ target.setId(source.getId().toString());
+
+ target.setNumber(source.getIndividualCount());
+ target.setWeight(source.getWeight());
+ target.setComment(source.getComments());
+
+ // Length step category
+ if (source.getSortingMeasurements().size() == 1) {
+ SortingMeasurement sm = source.getSortingMeasurements().iterator().next();
+ if (sm.getPmfm() != null && sm.getPmfm().getId() != null) {
+ Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(sm.getPmfm().getId());
+ target.setLengthStepCaracteristic(lengthStepCaracteristic);
+ }
+
+ // Length
+ target.setLengthStep(sm.getNumericalValue());
+ }
+ }
+
+ public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(
+ String speciesBatchId, List<SpeciesBatchFrequency> frequencies) {
+ Preconditions.checkNotNull(speciesBatchId);
+ Preconditions.checkNotNull(frequencies);
+
+ if (frequencies.size() == 0) {
+ return frequencies;
+ }
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ if (catchBatch == null) {
+ return frequencies;
+ }
+
+ // Retrieve parent
+ SortingBatch parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
+
+ // Remember child ids, to remove unchanged item (see at bottom in this method)
+ List<Integer> notUpdatedChildIds = Lists.newArrayList();
+ for (Iterator<Batch> iterator = parentBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch sortingBatch = (SortingBatch) iterator.next();
+ notUpdatedChildIds.add(sortingBatch.getId());
+ }
+
+ short rankOrder = 0;
+ String pmfmId = null;
+ List<SortingBatch> batchsToUpdate = Lists.newArrayList();
+ for (SpeciesBatchFrequency source : frequencies) {
+ rankOrder++;
+
+ // Check that all frequencies have the same length PMFM
+ if (pmfmId == null) {
+ source.getLengthStepCaracteristic().getId();
+ } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) {
+ throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic");
+ }
+
+ // Not existing batch
+ SortingBatch target = null;
+ if (source.getId() == null) {
+ target = SortingBatch.Factory.newInstance();
+
+ // Fill the sorting batch from the source
+ beanToEntity(source, target, parentBatch, rankOrder, true);
+
+ // Create the targeted batch, then update the source id
+ sortingBatchDao.create(target);
+ source.setId(target.getId().toString());
+ }
+
+ // Existing batch
+ else {
+ target = sortingBatchDao.load(Integer.valueOf(source.getId()));
+
+ // Fill the sorting batch from the source
+ beanToEntity(source, target, parentBatch, rankOrder, true);
+
+ // Add the batch into a list (will be update later, using this list)
+ batchsToUpdate.add(target);
+
+ notUpdatedChildIds.remove(target.getId());
+ }
+ }
+
+ // If some batchs need to be update, do it
+ if (batchsToUpdate.size() > 0) {
+ sortingBatchDao.update(batchsToUpdate);
+ }
+
+ if (notUpdatedChildIds.size() > 0) {
+ for (Iterator<Integer> iterator = notUpdatedChildIds.iterator(); iterator.hasNext();) {
+ Integer batchId = iterator.next();
+ catchBatchDao.removeWithChildren(batchId);
+ }
+ }
+
+ getCurrentSession().flush();
+
+ return frequencies;
+ }
+
+ // ------------------------------------------------------------------------//
+ // -- Internal methods --//
+ // ------------------------------------------------------------------------//
+
+ protected void validate(Collection<Batch> batchs, List<CatchBatchValidationError> errors, int treeLevel) {
+
+ List<Integer> expectedPmfms = null;
+ boolean expectedReferenceTaxon = false;
+ // First tree level : should have pmfm SORTED (Vrac, Hors Vrac, Non trié)
+ if (treeLevel == 1) {
+ expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+ // Second tree level : should have pmfm SORTING_TYPE (Species, Benthos...)
+ else if (treeLevel == 2) {
+ expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTING_TYPE);
+ }
+ else if (treeLevel == 3) {
+ expectedReferenceTaxon = true;
+ }
+ else if (treeLevel > 3) {
+ expectedPmfms = referentialService.getSampleCategoryIds();
+ expectedPmfms.remove(enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+
+ // First level : should be only PMFM=SORTED
+ for (Iterator<Batch> iterator = batchs.iterator(); iterator.hasNext();) {
+ SortingBatch batch = (SortingBatch) iterator.next();
+ boolean batchHasError = false;
+
+ // For all sorting measurements
+ if (batch.getSortingMeasurements() != null && batch.getSortingMeasurements().size() > 0) {
+ for (Iterator<SortingMeasurement> iterator2 = batch.getSortingMeasurements().iterator(); iterator2.hasNext();) {
+ SortingMeasurement sm = iterator2.next();
+ Integer pmfmId = sm.getPmfm().getId();
+ if (expectedReferenceTaxon) {
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.onlyTaxonButPmfmFound",
+ _("tutti.persistence.batch.validation.onlyTaxonButPmfmFound", batch.getId(), pmfmId),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+ else if (expectedPmfms.contains(pmfmId) == false) {
+ if (sm.getNumericalValue() == null || batch.getChildBatchs().size() > 0) {
+ batchHasError = true;
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.pmfmNotFound",
+ _("tutti.persistence.batch.validation.pmfmNotFound",
+ batch.getId(), Arrays.toString(expectedPmfms.toArray()), pmfmId),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+ }
+ }
+ }
+ else if (expectedPmfms != null && expectedPmfms.size() > 0){
+ batchHasError = true;
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.pmfmNotFound",
+ _("tutti.persistence.batch.validation.pmfmNotFound",
+ batch.getId(), Arrays.toString(expectedPmfms.toArray()), "null"),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+
+ if (!batchHasError && expectedReferenceTaxon == true && batch.getReferenceTaxon() == null) {
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.referenceTaxonNotFound",
+ _("tutti.persistence.batch.validation.referenceTaxonNotFound", batch.getId()),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+
+ if (!batchHasError) {
+ validate(batch.getChildBatchs(), errors, treeLevel+1);
+ }
+ }
+ }
+
+ protected void beanToEntity(SpeciesBatch source,
+ SortingBatch target,
+ String parentBatchId,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch,
+ boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // If parent and root need to be set
+ if (target.getId() == null
+ || target.getRootBatch() == null
+ || (target.getParentBatch() != null && !target.getParentBatch().getId().toString().equals(parentBatchId))) {
+ setBatchParents(source, target, parentBatchId, catchBatch);
+ }
+
+ // RankOrder (initialize once, at creation)
+ if (target.getRankOrder() == null) {
+ // Start rank order at 3, because of special batches 'Biota' and 'Inert'
+ short rankOrder = (short) 3;
+ if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) {
+ // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?)
+ rankOrder += (short) source.getParentBatch().getChildBatchs().size();
+ }
+ target.setRankOrder(rankOrder);
+ }
+
+ // Force subgroup count to '1', as Allegro
+ target.setSubgroupCount(1f);
+
+ // Weight or SampleCategoryWeight
+ if (copyIfNull && source.getWeight() == null && source.getSampleCategoryWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getSampleCategoryWeight() != null && source.getWeight() == null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sampling Ratio
+ if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) {
+ String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight();
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight());
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sorting measurement
+ if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) {
+ Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
+ // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch)
+ if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
+ SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId,
+ source.getSampleCategoryType(), source.getSampleCategoryValue());
+ notChangedSortingMeasurements.remove(sortingMeasurement);
+ }
+ }
+
+ // Individual count
+ if (copyIfNull && source.getNumber() == null) {
+ target.setIndividualCount(null);
+ } else if (source.getNumber() != null) {
+ target.setIndividualCount(source.getNumber());
+ }
+
+ // Species
+ if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) {
+ target.setReferenceTaxon(null);
+ } else if (source.getSpecies() != null && parentBatchId == null) {
+ ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId());
+ target.setReferenceTaxon(referenceTaxon);
+ }
+
+ // QualityFlag
+ if (source.isSpeciesToConfirm()) {
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL));
+ } else {
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ }
+
+ // Comments
+ if (copyIfNull && source.getComment() == null) {
+ target.setComments(null);
+ } else if (source.getComment() != null) {
+ target.setComments(source.getComment());
+ }
+
+ // Exhaustive inventory (always true under a species batch)
+ target.setExhaustiveInventory(true);
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ public void setBatchParents(SpeciesBatch source, SortingBatch target, String parentBatchIdStr,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+
+ Preconditions.checkNotNull(target);
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Load existing parent and root
+ SortingBatch parentBatch = null;
+ if (parentBatchIdStr != null) {
+ parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(parentBatchIdStr));
+ }
+
+ // Or retrieve parent batch, from pmfm id
+ else {
+ // Retrieve category type
+ Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
+ if (pmfmId == null || !pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
+ throw new DataIntegrityViolationException(MessageFormat.format(
+ "A species batch with no parent should have a sampleCategoryType {0} (PMFM.ID={1})",
+ SampleCategoryEnum.sortedUnsorted.name(),
+ enumeration.PMFM_ID_SORTED_UNSORTED));
+ }
+ Integer qualitativeValueId = convertSampleCategoryValueIntoQualitativeId(source.getSampleCategoryValue());
+
+ parentBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", pmfmId, qualitativeValueId,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ // Parent Batch
+ target.setParentBatch(parentBatch);
+ }
+
+
+ if (parentBatch == null) {
+ throw new DataIntegrityViolationException(
+ "Could not retrieve parent batch, for a given speciesBatch : invalid batch tree structure. Please make sure CatchBatch has been saved before to create a SpeciesBatch.");
+ }
+
+ // Parent Batch
+ target.setParentBatch(parentBatch);
+ target.setRootBatch(catchBatch);
+ }
+
+ Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) {
+ if (value == null)
+ return null;
+ Integer qualitativeValueId = null;
+ if (value instanceof CaracteristicQualitativeValue) {
+ CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value;
+ qualitativeValueId = Integer.valueOf(cqValue.getId());
+ } else if (value instanceof String) {
+ qualitativeValueId = Integer.valueOf((String) value);
+ }
+ return qualitativeValueId;
+ }
+
+ protected void setSampleCategoryQualitative(SpeciesBatch target, Integer pmfmId, Float numericalvalue, String alphanumericalValue,
+ Integer qualitativeValueId) {
+ // skip if null or corresponding to the SORTING_TYPE PMFM (Expèce, Benthos, Plancton, etc.)
+ if (pmfmId == null || pmfmId.equals(enumeration.PMFM_ID_SORTING_TYPE)) {
+ return;
+ }
+
+ SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
+ Preconditions.checkNotNull(sampleCategory, "Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId);
+
+ target.setSampleCategoryType(sampleCategory);
+ if (numericalvalue != null) {
+ target.setSampleCategoryValue(numericalvalue);
+ return;
+ }
+ if (alphanumericalValue != null) {
+ target.setSampleCategoryValue(alphanumericalValue);
+ return;
+ }
+
+ Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId);
+ if (caracteristic == null || caracteristic.getCaracteristicType() != CaracteristicType.QUALITATIVE) {
+ return;
+ }
+ CaracteristicQualitativeValue value = null;
+ for (CaracteristicQualitativeValue qv : caracteristic.getQualitativeValue()) {
+ if (qualitativeValueId == Integer.parseInt(qv.getId())) {
+ value = qv;
+ break;
+ }
+ }
+ target.setSampleCategoryValue(value);
+ }
+
+ protected void beanToEntity(SpeciesBatchFrequency source, SortingBatch target, SortingBatch parentBatch, short rankOrder, boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getBatch());
+ Preconditions.checkNotNull(source.getBatch().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // If parent and root need to be set
+ if (target.getId() == null
+ || target.getRootBatch() == null
+ || (target.getParentBatch() != null && !target.getParentBatch().getId().equals(parentBatch.getId()))) {
+
+ target.setParentBatch(parentBatch);
+ target.setRootBatch(parentBatch.getRootBatch());
+ }
+
+ // RankOrder
+ target.setRankOrder(rankOrder);
+
+ // Weight or SampleCategoryWeight
+ if (copyIfNull && source.getWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getWeight() != null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sorting measurement
+ if (copyIfNull && (source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getLengthStepCaracteristic() != null && source.getLengthStep() != null) {
+ Integer pmfmId = Integer.valueOf(source.getLengthStepCaracteristic().getId());
+ SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, pmfmId,
+ source.getLengthStep());
+ notChangedSortingMeasurements.remove(sortingMeasurement);
+ }
+
+ // Individual count
+ if (copyIfNull && source.getNumber() == null) {
+ target.setIndividualCount(null);
+ } else if (source.getNumber() != null) {
+ target.setIndividualCount(source.getNumber());
+ }
+
+ // Species
+ target.setReferenceTaxon(null);
+
+ // QualityFlag
+ target.setQualityFlag(parentBatch.getQualityFlag());
+
+ // Comments
+ if (copyIfNull && source.getComment() == null) {
+ target.setComments(null);
+ } else if (source.getComment() != null) {
+ target.setComments(source.getComment());
+ }
+
+ // Exhaustive inventory (always true under a species batch)
+ target.setExhaustiveInventory(true);
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected UIWeight convertDatabase2UI(Float weight, Float samplingRatio, String samplingRatioText) {
+ UIWeight result = new UIWeight();
+
+ // Weight & sampleCategory Weight
+ if (samplingRatio == null) {
+ result.sampleCategoryWeight = weight;
+ } else if (weight != null) {
+ String startStr = weight.toString().replace(',', '.') + "/";
+ if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
+ String weightStr = samplingRatioText.substring(startStr.length());
+ if (weightStr != null && !weightStr.isEmpty()) {
+ result.sampleCategoryWeight = Float.parseFloat(weightStr);
+ result.weight = weight;
+ }
+ } else {
+ result.sampleCategoryWeight = weight;
+ }
+ }
+ return result;
+ }
+
+ static class UIWeight {
+ Float sampleCategoryWeight = null;
+
+ Float weight = null;
+ }
+
+ protected void beanToEntity(CatchBatch source,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch target,
+ boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // First initialization (when created)
+ Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId());
+ target.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId));
+
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRankOrder((short) 1);
+ target.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue());
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+
+ // Total Weight
+ if (copyIfNull && source.getCatchTotalWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (source.getCatchTotalWeight() != null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getCatchTotalWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ Map<Integer, SortingBatch> catchBatchChilds = getChildsMap(target, enumeration.PMFM_ID_SORTED_UNSORTED);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac
+ // -----------------------------------------------------------------------------
+ {
+ SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_VRAC_ID);
+ if (batch == null) {
+ batch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(batch);
+ }
+ beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
+ source.getCatchTotalSortedCarousselWeight(), source.getCatchTotalSortedTremisWeight(),
+ copyIfNull);
+ batch.setRankOrder((short) 1);
+
+ // Manage childs :
+ {
+ Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species
+ // -----------------------------------------------------------------------------
+ SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ if (speciesBatch == null) {
+ speciesBatch = SortingBatch.Factory.newInstance();
+ if (batch.getChildBatchs() == null) {
+ batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
+ } else {
+ batch.getChildBatchs().add(speciesBatch);
+ }
+ }
+ beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
+ source.getSpeciesTotalSampleSortedWeight(), source.getSpeciesTotalSortedWeight(),
+ copyIfNull);
+ speciesBatch.setRankOrder((short) 1);
+
+ {
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species / Alive not itemized
+ // -----------------------------------------------------------------------------
+ SortingBatch aliveNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
+ if (aliveNotItemizedBatch == null) {
+ aliveNotItemizedBatch = SortingBatch.Factory.newInstance();
+ if (speciesBatch.getChildBatchs() == null) {
+ speciesBatch.setChildBatchs(Lists.newArrayList((Batch) aliveNotItemizedBatch));
+ } else {
+ speciesBatch.getChildBatchs().add(aliveNotItemizedBatch);
+ }
+ }
+ beanToEntityReferenceTaxonBatch(target, speciesBatch, aliveNotItemizedBatch, recorderDepartmentId,
+ enumeration.REFERENCE_TAXON_ID_LIFE,
+ source.getSpeciesTotalLivingNotItemizedWeight(), null,
+ copyIfNull);
+ aliveNotItemizedBatch.setRankOrder((short) 1);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species / Inert (not alive)
+ // -----------------------------------------------------------------------------
+ SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
+ if (inertBatch == null) {
+ inertBatch = SortingBatch.Factory.newInstance();
+ speciesBatch.getChildBatchs().add(inertBatch);
+ }
+ beanToEntityReferenceTaxonBatch(target, speciesBatch, inertBatch, recorderDepartmentId,
+ enumeration.REFERENCE_TAXON_ID_INERT,
+ source.getSpeciesTotalInertWeight(), null,
+ copyIfNull);
+ inertBatch.setRankOrder((short) 2);
+ }
+ }
+ // TODO BL : benthos, plancton, macro déchet...
+ }
+
+ // -----------------------------------------------------------------------------
+ // Sorted Hors Vrac
+ // -----------------------------------------------------------------------------
+ {
+ SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_HORS_VRAC_ID);
+ if (batch == null) {
+ batch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(batch);
+ }
+ beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
+ source.getCatchTotalUnsortedWeight(), null,
+ copyIfNull);
+ batch.setRankOrder((short) 2);
+
+ // Manage childs :
+ {
+ Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
+
+ // Species :
+ SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ if (speciesBatch == null) {
+ speciesBatch = SortingBatch.Factory.newInstance();
+ if (batch.getChildBatchs() == null) {
+ batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
+ } else {
+ batch.getChildBatchs().add(speciesBatch);
+ }
+ }
+ beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
+ source.getSpeciesTotalUnsortedWeight(), null,
+ copyIfNull);
+ speciesBatch.setRankOrder((short) 1);
+ }
+
+ // TODO BL : benthos, plancton, macro déchet...
+ }
+
+ // -----------------------------------------------------------------------------
+ // Unsorted (=rejected)
+ // -----------------------------------------------------------------------------
+ // Unsorted :
+ SortingBatch unsortedBatch = catchBatchChilds.get(enumeration.QUALITATIVE_UNSORTED_ID);
+ if (unsortedBatch == null) {
+ unsortedBatch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(unsortedBatch);
+ }
+ beanToEntitySortingBatch(target, target, unsortedBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID,
+ source.getCatchTotalRejectedWeight(), null,
+ copyIfNull);
+ unsortedBatch.setRankOrder((short) 3);
+
+ }
+
+ protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) {
+ Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
+ if (parentBatch.getChildBatchs() == null) {
+ return batchByQualitativeValueId;
+ }
+ for (Batch childBatch : parentBatch.getChildBatchs()) {
+ SortingBatch childSortingBatch = (SortingBatch) childBatch;
+ SortingMeasurement sm = measurementHelper.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false);
+ if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) {
+ batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), childSortingBatch);
+ }
+ }
+ return batchByQualitativeValueId;
+ }
+
+ /**
+ * Retrieve child batchs if species is "Life" or "No life"
+ * (need to retrieve: speciesTotalLivingNotItemizedWeight and speciesTotalInertWeight)
+ *
+ * @param parentBatch
+ * @return
+ */
+ protected Map<Integer, SortingBatch> getChildAliveNotSortedOrInert(Batch parentBatch) {
+ Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
+ if (parentBatch.getChildBatchs() == null) {
+ return batchByQualitativeValueId;
+ }
+ for (Batch childBatch : parentBatch.getChildBatchs()) {
+ SortingBatch childSortingBatch = (SortingBatch) childBatch;
+ if (childSortingBatch.getReferenceTaxon() != null && childSortingBatch.getId().intValue() < 0) {
+ if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
+ batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
+ } else if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
+ batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
+ }
+ }
+ }
+ return batchByQualitativeValueId;
+ }
+
+ protected void beanToEntitySortingBatch(
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
+ fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
+ fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
+ Integer recorderDepartmentId,
+ Integer sortingPmfmId,
+ Integer sortingQualitativeValueId,
+ Float weight,
+ Float sampleWeight,
+ boolean copyIfNull) {
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // Some mandatory properties :
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRootBatch(rootBatch);
+ target.setParentBatch(parentBatch);
+ target.setExhaustiveInventory(true);
+
+ // No taxon or taxon group
+ target.setReferenceTaxon(null);
+ target.setTaxonGroup(null);
+
+ // Sorting measurement
+ if (copyIfNull && (sortingPmfmId == null || sortingQualitativeValueId == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (sortingPmfmId != null && sortingQualitativeValueId != null) {
+ SortingMeasurement sm = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId);
+ notChangedSortingMeasurements.remove(sm);
+ }
+
+ // Sampling Ratio
+ if (copyIfNull && (sampleWeight == null || weight == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (sampleWeight != null && weight != null) {
+ String samplingRatioText = weight + "/" + sampleWeight;
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(weight / sampleWeight);
+ }
+
+ // Weight
+ if (copyIfNull && (sampleWeight == null && weight == null)) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (sampleWeight != null || weight != null) {
+ Float batchReferenceWeight = weight;
+ if (batchReferenceWeight == null) {
+ batchReferenceWeight = sampleWeight;
+ }
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected void beanToEntityReferenceTaxonBatch(
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
+ fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
+ fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
+ Integer recorderDepartmentId,
+ Integer referenceTaxonId,
+ Float weight,
+ Float sampleWeight,
+ boolean copyIfNull) {
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // Some mandatory properties :
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRootBatch(rootBatch);
+ target.setParentBatch(parentBatch);
+ target.setExhaustiveInventory(true);
+
+ // Reference taxon
+ target.setReferenceTaxon(load(ReferenceTaxonImpl.class, referenceTaxonId));
+ target.setTaxonGroup(null);
+
+ // Sampling Ratio
+ if (copyIfNull && (sampleWeight == null || weight == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (sampleWeight != null && weight != null) {
+ String samplingRatioText = weight + "/" + sampleWeight;
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(weight / sampleWeight);
+ }
+
+ // Weight
+ if (copyIfNull && (sampleWeight == null && weight == null)) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (sampleWeight != null || weight != null) {
+ Float batchReferenceWeight = weight;
+ if (batchReferenceWeight == null) {
+ batchReferenceWeight = sampleWeight;
+ }
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected Integer getRecorderDepartmentId() {
+ // TODO BL : voir si on peut récupérer le departement (du 1er saisisseur ?)
+ return enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
+ }
+}
\ No newline at end of file
Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -27,6 +27,7 @@
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
+import fr.ifremer.tutti.persistence.ProgressionModel;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
@@ -83,26 +84,32 @@
* @param localProperties properties to connect to local database
* @param remoteProperties properties to connect to remove database
* @param dialect dialect used to seek metadata of databases.
- * @return Result of the synchronize operation, if there is an error then
- * the {@link ReferentialSynchronizeResult#isSuccess()} is {@code false}
- * and you can get the error at
- * {@link ReferentialSynchronizeResult#getError()}
+ * @param result Result of the synchronize operation, if there is an error then
+ * the {@link ReferentialSynchronizeResult#isSuccess()} is {@code false}
+ * and you can get the error at
+ * {@link ReferentialSynchronizeResult#getError()}
*/
- public ReferentialSynchronizeResult synchronize(Properties localProperties,
- Properties remoteProperties,
- Dialect dialect) {
+ public void prepare(Properties localProperties,
+ Properties remoteProperties,
+ Dialect dialect,
+ ReferentialSynchronizeResult result) {
- ReferentialSynchronizeResult result = new ReferentialSynchronizeResult(
- TuttiEntities.getUrl(localProperties),
- TuttiEntities.getUrl(remoteProperties));
+ result.setLocalUrl(TuttiEntities.getUrl(localProperties));
+ result.setRemoteUrl(TuttiEntities.getUrl(remoteProperties));
+
Connection localConnection = null;
Connection remoteConnection = null;
try {
+ ProgressionModel progressionModel = result.getProgressionModel();
+ progressionModel.setMessage("Connection à la base de synchronisation");
+
// create local connection
localConnection = TuttiEntities.createConnection(localProperties);
+ progressionModel.setMessage("Connection à la base à synchroniser");
+
// create remote Connection
remoteConnection = TuttiEntities.createConnection(remoteProperties);
@@ -112,6 +119,8 @@
TuttiDatabaseMetadata remoteMeta =
loadDatabaseMetadata(remoteConnection, dialect);
+ progressionModel.setMessage("Vérification de la compatibilité des schémas");
+
// check schema
try {
checkSchemas(localMeta, remoteMeta);
@@ -127,6 +136,8 @@
String tableName = tuttiTable.name();
+ progressionModel.setMessage("Lecture de la table " + tableName);
+
TuttiTableMetadata table = remoteMeta.getTable(tableName);
if (log.isDebugEnabled()) {
@@ -142,40 +153,100 @@
if (log.isInfoEnabled()) {
log.info("Total rows to update: " + totalRows);
}
+ localConnection.rollback();
+ }
+ } catch (SQLException e) {
+ try {
+ if (localConnection != null) {
+ localConnection.rollback();
+ }
+ } catch (SQLException e1) {
- // prepare target (desactivate constraints)
- prepareSynch(localConnection);
+ // ignore the rolback error
+ }
+ result.setError(e);
+ } finally {
+ JdbcUtils.closeConnection(remoteConnection);
+ JdbcUtils.closeConnection(localConnection);
+ }
+ }
- try {
- for (TuttiTable tuttiTable : TuttiTable.values()) {
+ /**
+ * Synchronize database given from {@code localProperties} (means the
+ * database to update) with remote database (means the database which
+ * contains the referential to use) given by {@code remoteProperties}
+ * using the given {@code dialect} to inspect databases metadatas.
+ *
+ * @param localProperties properties to connect to local database
+ * @param remoteProperties properties to connect to remove database
+ * @param dialect dialect used to seek metadata of databases.
+ * @return Result of the synchronize operation, if there is an error then
+ * the {@link ReferentialSynchronizeResult#isSuccess()} is {@code false}
+ * and you can get the error at
+ * {@link ReferentialSynchronizeResult#getError()}
+ */
+ public ReferentialSynchronizeResult synchronize(Properties localProperties,
+ Properties remoteProperties,
+ Dialect dialect,
+ ReferentialSynchronizeResult result) {
- String tableName = tuttiTable.name();
- TuttiTableMetadata table = remoteMeta.getTable(tableName);
+ Connection localConnection = null;
+ Connection remoteConnection = null;
+ try {
- if (log.isInfoEnabled()) {
- log.info("Synchronize table: " + tableName);
- }
- synchronizeTable(table,
- localConnection,
- remoteConnection,
- result);
- }
+ // create local connection
+ localConnection = TuttiEntities.createConnection(localProperties);
+
+ // create remote Connection
+ remoteConnection = TuttiEntities.createConnection(remoteProperties);
+
+ // load metas
+ TuttiDatabaseMetadata remoteMeta =
+ loadDatabaseMetadata(remoteConnection, dialect);
+
+ // set total in progression model
+ ProgressionModel progressionModel = result.getProgressionModel();
+ progressionModel.setTotal(result.getTotalRows());
+
+ // prepare target (desactivate constraints)
+ prepareSynch(localConnection);
+
+ try {
+
+ for (TuttiTable tuttiTable : TuttiTable.values()) {
+
+ String tableName = tuttiTable.name();
+
+ progressionModel.setMessage("Mise à jour de la table " + tableName);
+
+ TuttiTableMetadata table = remoteMeta.getTable(tableName);
+
if (log.isInfoEnabled()) {
- long totalInserts = result.getTotalInserts();
- long totalUpdates = result.getTotalUpdates();
- log.info("Total rows to treat: " + totalRows);
- log.info("Total rows inserted: " + totalInserts);
- log.info("Total rows updated: " + totalUpdates);
- log.info("Total rows treated: " + (totalInserts + totalUpdates));
+ log.info("Synchronize table: " + tableName);
}
- } finally {
- releaseSynch(localConnection);
+ synchronizeTable(table,
+ localConnection,
+ remoteConnection,
+ result);
}
+ if (log.isInfoEnabled()) {
+ long totalInserts = result.getTotalInserts();
+ long totalUpdates = result.getTotalUpdates();
+ log.info("Total rows to treat: " + result.getTotalRows());
+ log.info("Total rows inserted: " + totalInserts);
+ log.info("Total rows updated: " + totalUpdates);
+ log.info("Total rows treated: " + (totalInserts + totalUpdates));
+ }
+ } finally {
+ releaseSynch(localConnection);
+ }
- localConnection.commit();
- }
+ progressionModel.setMessage("Sauvegarde des données dans la base locale");
+
+ localConnection.commit();
+
} catch (SQLException e) {
try {
if (localConnection != null) {
@@ -446,6 +517,10 @@
countR++;
+ if (countR % 1000 == 0) {
+ result.getProgressionModel().increments(1000);
+ }
+
if (insertCount > 0 && insertCount % 1000 == 0) {
insertStatement.executeBatch();
insertStatement.clearBatch();
@@ -480,6 +555,8 @@
log.debug(String.format("%s INSERT count: %s", tablePrefix, result.getNbInserts(tableName)));
log.debug(String.format("%s UPDATE count: %s", tablePrefix, result.getNbUpdates(tableName)));
}
+
+ result.getProgressionModel().increments(countR % 1000);
}
protected String getTablePrefix(TuttiTableMetadata table) {
@@ -494,6 +571,8 @@
String tableName = table.getName();
+ result.getProgressionModel().setMessage("Mise à jour de la table " + tableName);
+
String tablePrefix = getTablePrefix(table);
// get last updateDate used by local db
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -27,6 +27,7 @@
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+import fr.ifremer.tutti.persistence.ProgressionModel;
import java.sql.Timestamp;
import java.util.Map;
@@ -77,15 +78,28 @@
*/
protected final Set<String> tableNames = Sets.newHashSet();
- protected final String localUrl;
+ protected String localUrl;
- protected final String remoteUrl;
+ protected String remoteUrl;
+ protected final ProgressionModel progressionModel = new ProgressionModel();
+
+ public ReferentialSynchronizeResult() {
+ }
+
public ReferentialSynchronizeResult(String localUrl, String remoteUrl) {
this.localUrl = localUrl;
this.remoteUrl = remoteUrl;
}
+ public void setLocalUrl(String localUrl) {
+ this.localUrl = localUrl;
+ }
+
+ public void setRemoteUrl(String remoteUrl) {
+ this.remoteUrl = remoteUrl;
+ }
+
public boolean isSuccess() {
return error == null;
}
@@ -98,28 +112,32 @@
this.error = error;
}
+ public ProgressionModel getProgressionModel() {
+ return progressionModel;
+ }
+
public Set<String> getTableNames() {
return ImmutableSet.copyOf(tableNames);
}
- public long getTotalRows() {
- long result = 0;
+ public int getTotalRows() {
+ int result = 0;
for (Integer nb : rowHits.values()) {
result += nb;
}
return result;
}
- public long getTotalInserts() {
- long result = 0;
+ public int getTotalInserts() {
+ int result = 0;
for (Integer nb : insertHits.values()) {
result += nb;
}
return result;
}
- public long getTotalUpdates() {
- long result = 0;
+ public int getTotalUpdates() {
+ int result = 0;
for (Integer nb : updateHits.values()) {
result += nb;
}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeService.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeService.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -55,13 +55,27 @@
Dialect getLocalDialect();
/**
+ * Prepare the synchronize operation from the local data database supported
+ * by this service, says just compute nb rows to update for each table and
+ * update the result model.
+ *
+ * @param remoteConnectionProperties connection properties of the remote
+ * database used to synchronize referential
+ * @param result result of the operation
+ * @see ReferentialSynchronizeResult
+ */
+ void prepare(Properties remoteConnectionProperties,
+ ReferentialSynchronizeResult result);
+
+ /**
* Launch the synchronize operation from the local data database supported
* by this service.
*
* @param remoteConnectionProperties connection properties of the remote
* database used to synchronize referential
- * @return result of the operation
+ * @param result model
* @see ReferentialSynchronizeResult
*/
- ReferentialSynchronizeResult synchronize(Properties remoteConnectionProperties);
+ void synchronize(Properties remoteConnectionProperties,
+ ReferentialSynchronizeResult result);
}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -24,6 +24,7 @@
* #L%
*/
+import com.google.common.base.Preconditions;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import fr.ifremer.tutti.persistence.service.AbstractPersistenceService;
import org.apache.commons.dbcp.BasicDataSource;
@@ -75,10 +76,26 @@
}
@Override
- public ReferentialSynchronizeResult synchronize(Properties remoteConnectionProperties) {
+ public void prepare(Properties remoteConnectionProperties, ReferentialSynchronizeResult result) {
+ Preconditions.checkNotNull(result);
+ Preconditions.checkNotNull(remoteConnectionProperties);
+ helper.prepare(getLocalConnectionProperties(),
+ remoteConnectionProperties,
+ getLocalDialect(),
+ result);
+ }
+
+ @Override
+ public void synchronize(Properties remoteConnectionProperties, ReferentialSynchronizeResult result) {
//TODO Evict all caches, restart application (but not from here,...)
- return helper.synchronize(getLocalConnectionProperties(),
- remoteConnectionProperties,
- getLocalDialect());
+
+ Preconditions.checkNotNull(result);
+ Preconditions.checkNotNull(remoteConnectionProperties);
+ Preconditions.checkState(result.isSuccess());
+
+ helper.synchronize(getLocalConnectionProperties(),
+ remoteConnectionProperties,
+ getLocalDialect(),
+ result);
}
}
Modified: trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties
===================================================================
--- trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties 2013-02-14 23:53:34 UTC (rev 414)
@@ -380,5 +380,5 @@
#Reference taxon correspondant à "Biota" (ou "Vie")
ReferenceTaxonId.LIFE=7637
#Reference taxon correspondant à "Non Biota" (ou "Non Vie" - matière inerte)
-# TODO : a creer dans la base harmonie et a�changer !
+# TODO : a creer dans la base harmonie et achanger !
ReferenceTaxonId.INERT=1
\ No newline at end of file
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -270,7 +270,7 @@
if (p != null) {
TuttiEntities.fillConnectionProperties(
p,
- "jdbc:hsqldb:file:" + target.getAbsolutePath() + "/" + config.getDbName(),
+ TuttiEntities.getJdbcUrl(target, config.getDbName()),
config.getJdbcUsername(),
config.getJdbcPassword());
}
@@ -377,7 +377,7 @@
log.info("Create new db at " + directory);
}
addToDestroy(directory);
- String jdbcUrl = "jdbc:hsqldb:file:" + directory.getAbsolutePath() + "/" + dbName;
+ String jdbcUrl = TuttiEntities.getJdbcUrl(directory, dbName);
String user = "SA";
String password = "";
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -1,187 +1,187 @@
-package fr.ifremer.tutti.persistence.service;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id: CatchBatchPersistenceServiceReadTest.java 379 2013-02-10 13:41:29Z tchemit $
- * $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/test/j… $
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * 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%
- */
-
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.List;
-import java.util.Map;
-
-import fr.ifremer.tutti.persistence.DatabaseResource;
-import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
-import fr.ifremer.tutti.persistence.entities.data.Cruise;
-import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
-import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
-
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.springframework.dao.DataRetrievalFailureException;
-
-import com.google.common.collect.Maps;
-
-/**
- * To test {@link CatchBatchPersistenceService} for read operation.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.0
- */
-public class BatchPersistenceServiceReadTest {
-
- @ClassRule
- public static final DatabaseResource dbResource = DatabaseResource.readDb();
-
- protected BatchPersistenceService service;
- protected FishingOperationPersistenceService fishingOperationService;
- protected FishingOperation fishingOperation;
-
- @Before
- public void setUp() throws Exception {
- service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
- fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
-
- List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
- assertNotNull(fishingOperations);
- assertTrue(fishingOperations.size() > 0);
- fishingOperation = fishingOperations.get(0);
- assertNotNull(fishingOperation);
- assertNotNull(fishingOperation.getId());
- }
-
- @Test
- public void getCatchBatchFromFishingOperation() throws Exception {
-
- try {
- CatchBatch catchBatch = service.getCatchBatchFromFishingOperation(fishingOperation.getId());
- fail("batch tree must be invalid (old CGFS tree structure), for fishing operation id=" + fishingOperation.getId());
- }
- catch(DataRetrievalFailureException drfe) {
- // success
- }
- }
-
- @Test
- public void getAllRootSpeciesBatch(/*String fishingOperationId*/) {
- }
-
- @Test
- public void getAllSpeciesBatchFrequency(/*String speciesBatchId*/) {
-
- }
-
- public static void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
- assertNotNull(actualBatch);
- assertNotNull(actualBatch.getId());
- if (assertIdEquals && expectedBatch.getId() != null) {
- assertEquals(expectedBatch.getId(), actualBatch.getId());
- }
- assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
- assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
- if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
- assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
- actualBatch.getSampleCategoryValue());
- assertEquals(
- ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
- ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
- } else {
- assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
- }
- assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
- assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
- assertEquals(expectedBatch.getComment(), actualBatch.getComment());
-
- // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
- // (Because getSpeciesBatch(id) could not always retrieve the species)
- if (expectedBatch.getSpecies() != null && (
- expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
- || actualBatch.getSpecies() != null)) {
- assertNotNull(actualBatch.getSpecies());
- assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
- }
- }
-
- public static void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
- assertNotNull(actualFrequencies);
- assertEquals(expectedFrequencies.size(), actualFrequencies.size());
-
- // Store actual batches into a map, using the length as key
- Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
- for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
- expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
- }
-
- // Store expected batches into a map, using the length as key
- Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
- for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
- assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
- actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
- assertNotNull(speciesBatchFrequency.getId());
- }
-
- for (Float lengthStep : expectedLengthMap.keySet()) {
- SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
- SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
- if (assertIdEquals) {
- assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
- }
- assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
- assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
- assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
- assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
- assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
- //assertNotNull(expectedBatchFrequency.getBatch());
- //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
- }
- }
-
- public static SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
- return getSpeciesBatch(speciesBatchId, TuttiPersistenceServiceLocator.getBatchPersistenceService().getAllRootSpeciesBatch(fishingOperationId));
- }
-
- public static SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
- if (speciesBatchs == null) {
- return null;
- }
- for (SpeciesBatch speciesBatch : speciesBatchs) {
- if (speciesBatchId.equals(speciesBatch.getId())) {
- return speciesBatch;
- }
- if (speciesBatch.getChildBatchs() != null) {
- speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
- if (speciesBatch != null) {
- return speciesBatch;
- }
- }
- }
- return null;
- }
-
-}
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.Cruise;
+import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.springframework.dao.DataRetrievalFailureException;
+
+import com.google.common.collect.Maps;
+
+/**
+ * To test {@link CatchBatchPersistenceService} for read operation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class BatchPersistenceServiceReadTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.readDb();
+
+ protected BatchPersistenceService service;
+ protected FishingOperationPersistenceService fishingOperationService;
+ protected FishingOperation fishingOperation;
+
+ @Before
+ public void setUp() throws Exception {
+ service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
+ fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
+
+ List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
+ assertNotNull(fishingOperations);
+ assertTrue(fishingOperations.size() > 0);
+ fishingOperation = fishingOperations.get(0);
+ assertNotNull(fishingOperation);
+ assertNotNull(fishingOperation.getId());
+ }
+
+ @Test
+ public void getCatchBatchFromFishingOperation() throws Exception {
+
+ try {
+ CatchBatch catchBatch = service.getCatchBatchFromFishingOperation(fishingOperation.getId());
+ fail("batch tree must be invalid (old CGFS tree structure), for fishing operation id=" + fishingOperation.getId());
+ }
+ catch(DataRetrievalFailureException drfe) {
+ // success
+ }
+ }
+
+ @Test
+ public void getAllRootSpeciesBatch(/*String fishingOperationId*/) {
+ }
+
+ @Test
+ public void getAllSpeciesBatchFrequency(/*String speciesBatchId*/) {
+
+ }
+
+ public static void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
+ assertNotNull(actualBatch);
+ assertNotNull(actualBatch.getId());
+ if (assertIdEquals && expectedBatch.getId() != null) {
+ assertEquals(expectedBatch.getId(), actualBatch.getId());
+ }
+ assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
+ assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
+ if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
+ assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
+ actualBatch.getSampleCategoryValue());
+ assertEquals(
+ ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
+ ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
+ } else {
+ assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
+ }
+ assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
+ assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
+ assertEquals(expectedBatch.getComment(), actualBatch.getComment());
+
+ // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
+ // (Because getSpeciesBatch(id) could not always retrieve the species)
+ if (expectedBatch.getSpecies() != null && (
+ expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
+ || actualBatch.getSpecies() != null)) {
+ assertNotNull(actualBatch.getSpecies());
+ assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
+ }
+ }
+
+ public static void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
+ assertNotNull(actualFrequencies);
+ assertEquals(expectedFrequencies.size(), actualFrequencies.size());
+
+ // Store actual batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
+ expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ }
+
+ // Store expected batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
+ assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
+ actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ assertNotNull(speciesBatchFrequency.getId());
+ }
+
+ for (Float lengthStep : expectedLengthMap.keySet()) {
+ SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
+ SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
+ if (assertIdEquals) {
+ assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
+ }
+ assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
+ assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
+ assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
+ assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
+ assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
+ //assertNotNull(expectedBatchFrequency.getBatch());
+ //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
+ }
+ }
+
+ public static SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
+ return getSpeciesBatch(speciesBatchId, TuttiPersistenceServiceLocator.getBatchPersistenceService().getAllRootSpeciesBatch(fishingOperationId));
+ }
+
+ public static SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
+ if (speciesBatchs == null) {
+ return null;
+ }
+ for (SpeciesBatch speciesBatch : speciesBatchs) {
+ if (speciesBatchId.equals(speciesBatch.getId())) {
+ return speciesBatch;
+ }
+ if (speciesBatch.getChildBatchs() != null) {
+ speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
+ if (speciesBatch != null) {
+ return speciesBatch;
+ }
+ }
+ }
+ return null;
+ }
+
+}
Property changes on: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -1,621 +1,621 @@
-package fr.ifremer.tutti.persistence.service;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id: CatchBatchPersistenceServiceWriteTest.java 379 2013-02-10 13:41:29Z tchemit $
- * $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/test/j… $
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * 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%
- */
-
-import fr.ifremer.tutti.persistence.DatabaseResource;
-import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
-import fr.ifremer.tutti.persistence.entities.data.Cruise;
-import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
-import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
-import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
-import fr.ifremer.tutti.persistence.entities.referential.Species;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.springframework.dao.DataRetrievalFailureException;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.List;
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.*;
-
-/**
- * To test {@link CatchBatchPersistenceService} for write operation.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.0
- */
-public class BatchPersistenceServiceWriteTest {
-
- @ClassRule
- public static final DatabaseResource dbResource = DatabaseResource.writeDb();
-
- protected BatchPersistenceService service;
-
- protected CruisePersistenceService cruiseService;
-
- protected FishingOperationPersistenceService fishingOperationService;
-
- protected CatchBatchPersistenceService catchBatchService;
-
- protected ReferentialPersistenceService referentialService;
-
- protected Cruise cruise;
-
- protected FishingOperation fishingOperationNoCatchBatch;
-
- protected FishingOperation fishingOperationWithEmptyBatch;
-
- protected CatchBatch catchBacth;
-
- protected List<Species> species;
-
- protected Caracteristic sortedUnsortedPMFM;
-
- protected CaracteristicQualitativeValue horsVracQualitativeValue;
-
- protected CaracteristicQualitativeValue vracQualitativeValue;
-
- protected Caracteristic maturityPMFM;
-
- protected CaracteristicQualitativeValue firstMaturityQualitativeValue;
-
- protected Caracteristic sexPMFM;
-
- protected CaracteristicQualitativeValue maleQualitativeValue;
-
- protected CaracteristicQualitativeValue femaleQualitativeValue;
-
- protected CaracteristicQualitativeValue unkQualitativeValue;
-
- protected Caracteristic frequencyPMFM;
-
- @Before
- public void setUp() throws Exception {
- service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
- cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService();
- fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
- catchBatchService = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService();
- referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService();
-
- species = referentialService.getAllSpecies();
- assertNotNull(species);
- assertTrue(species.size() > 2);
-
- cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId());
- cruise.setId(null);
- Calendar calendar = new GregorianCalendar();
- cruise.setBeginDate(calendar.getTime());
- cruise.setYear(calendar.get(Calendar.YEAR));
- calendar.add(Calendar.MONTH, 1); // add one month
- cruise.setEndDate(calendar.getTime());
- cruise = cruiseService.createCruise(cruise);
-
- // Create a first operation, with no cacth batch : to test CatchBatch insert/update :
- List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
- assertNotNull(fishingOperations);
- assertTrue(fishingOperations.size() > 0);
- fishingOperationNoCatchBatch = fishingOperations.get(0);
- fishingOperationNoCatchBatch = fishingOperationService.getFishingOperation(fishingOperationNoCatchBatch.getId());
- fishingOperationNoCatchBatch.setId(null);
- fishingOperationNoCatchBatch.setCruise(cruise);
- calendar.setTime(new Date());
- calendar.set(Calendar.HOUR_OF_DAY, 1);
- calendar.set(Calendar.MILLISECOND, 0);
- fishingOperationNoCatchBatch.setGearShootingStartDate(calendar.getTime());
- calendar.setTime(new Date());
- calendar.set(Calendar.HOUR_OF_DAY, 10);
- calendar.set(Calendar.MILLISECOND, 0);
- fishingOperationNoCatchBatch.setGearShootingEndDate(calendar.getTime());
- fishingOperationNoCatchBatch = fishingOperationService.createFishingOperation(fishingOperationNoCatchBatch);
-
- // Create a second operation, with no cacth batch : to test CatchBatch insert/update :
- fishingOperationWithEmptyBatch = fishingOperations.get(1);
- fishingOperationWithEmptyBatch = fishingOperationService.getFishingOperation(fishingOperationWithEmptyBatch.getId());
- fishingOperationWithEmptyBatch.setId(null);
- fishingOperationWithEmptyBatch.setCruise(cruise);
- calendar.setTime(new Date());
- calendar.set(Calendar.HOUR_OF_DAY, 11);
- calendar.set(Calendar.MILLISECOND, 0);
- fishingOperationWithEmptyBatch.setGearShootingStartDate(calendar.getTime());
- calendar.setTime(new Date());
- calendar.set(Calendar.HOUR_OF_DAY, 12);
- calendar.set(Calendar.MILLISECOND, 0);
- fishingOperationWithEmptyBatch.setGearShootingEndDate(calendar.getTime());
- fishingOperationWithEmptyBatch = fishingOperationService.createFishingOperation(fishingOperationWithEmptyBatch);
-
- catchBacth = new CatchBatch();
- catchBacth.setFishingOperation(fishingOperationWithEmptyBatch);
- catchBacth = catchBatchService.createCatchBatch(catchBacth);
-
- sortedUnsortedPMFM = referentialService.getSortedUnsortedCaracteristic();
- horsVracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(0);
- vracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(1);
- maturityPMFM = referentialService.getMaturityCaracteristic();
- firstMaturityQualitativeValue = maturityPMFM.getQualitativeValue(0);
- sexPMFM = referentialService.getSexCaracteristic();
- maleQualitativeValue = sexPMFM.getQualitativeValue(1);
- femaleQualitativeValue = sexPMFM.getQualitativeValue(2);
- unkQualitativeValue = sexPMFM.getQualitativeValue(3);
-
- List<Caracteristic> cara = referentialService.getAllCaracteristic();
- for (Caracteristic caracteristic : cara) {
- if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER
- && caracteristic.getPrecision() != null
- && caracteristic.getPrecision() == 0.5f) {
- frequencyPMFM = caracteristic;
- break;
- }
- }
- assertNotNull("no numerical PMFM with a precision has been found. Could not define a PMFM for batch frequencies.", frequencyPMFM);
-
- }
-
- @Test
- public void createAndSaveCatchBatch() throws Exception {
- CatchBatch catchBatch;
-
- catchBatch = new CatchBatch();
- catchBatch.setFishingOperation(fishingOperationNoCatchBatch);
-
- // -----------------------------------------------------------------------------
- // 1. Test with only mandatory properties
- // -----------------------------------------------------------------------------
-
- // Create and reload (test round trip)
- assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
-
- // -----------------------------------------------------------------------------
- // 2. Test with all properties
- // -----------------------------------------------------------------------------
- catchBatch.setId(null);
- // total weight : 100kg
- catchBatch.setCatchTotalWeight(75f);
- // Vrac :
- {
- // note : poids trie par la balance tremis (thalassa) (init par pupitri)
- catchBatch.setCatchTotalSortedTremisWeight(50f);
- // note : poids vrac caroussel (thalassa) (init par pupitri) (vrac trie) ou bien "poids trié fournie par la table de tri (Sum(Si)
- catchBatch.setCatchTotalSortedCarousselWeight(45f);
-
- // Species
- {
- catchBatch.setSpeciesTotalSortedWeight(12f);
- catchBatch.setSpeciesTotalSampleSortedWeight(8f);
- catchBatch.setSpeciesTotalLivingNotItemizedWeight(0.2f);
- catchBatch.setSpeciesTotalInertWeight(0.1f);
- }
- }
- // Hors Vrac : 10kg
- {
- catchBatch.setCatchTotalUnsortedWeight(10f);
-
- // Species
- {
- catchBatch.setSpeciesTotalUnsortedWeight(10f);
- }
- }
- // Rejet : 15kg
- catchBatch.setCatchTotalRejectedWeight(15f);
-
- // Create and reload (test round trip)
- assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
-
- // -----------------------------------------------------------------------------
- // 2. Test save after modification
- // -----------------------------------------------------------------------------
- catchBatch.setCatchTotalSortedTremisWeight(null);
- catchBatch.setCatchTotalSortedCarousselWeight(null);
- catchBatch.setSpeciesTotalSortedWeight(null);
- catchBatch.setSpeciesTotalSampleSortedWeight(null);
- catchBatch.setCatchTotalUnsortedWeight(null);
- catchBatch.setSpeciesTotalUnsortedWeight(null);
-
- assertSaveAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
- }
-
- @Test
- public void createAndSaveSpeciesBatchAndFrequencies() {
- SpeciesBatch esp1Batch = null;
- SpeciesBatch esp2Batch = null;
- SpeciesBatch frequenciesParentBatch = null;
- SpeciesBatch batch = null;
- Species taxon1 = species.get(0);
- Species taxon2 = species.get(1);
-
- // -----------------------------------------------------------------------------
- // 1. Test with only mandatory properties
- // -----------------------------------------------------------------------------
- // batch : "ESP1 - Vrac/5"
- batch = new SpeciesBatch();
- batch.setParentBatch(null);
- batch.setFishingOperation(fishingOperationNoCatchBatch);
- batch.setSpecies(taxon1);
- batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
- batch.setSampleCategoryValue(vracQualitativeValue);
- batch.setSampleCategoryWeight(5f);
-
- assertCreateAndReloadSpeciesBatch(batch, null);
-
- // Save ESP1 batch
- esp1Batch = batch;
-
- // -----------------------------------------------------------------------------
- // 2. Test child "Male/2"
- // -----------------------------------------------------------------------------
- // Batch : ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7
- batch = new SpeciesBatch();
- batch.setId(null);
- batch.setParentBatch(esp1Batch);
- batch.setSpecies(taxon1);
- batch.setComment("ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7");
- batch.setSampleCategoryType(SampleCategoryEnum.sex);
- batch.setSampleCategoryValue(maleQualitativeValue);
- batch.setSampleCategoryWeight(2f);
- batch.setWeight(1f);
- batch.setNumber(7);
-
- assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
-
- // -----------------------------------------------------------------------------
- // 3. Test child "Female/2"
- // -----------------------------------------------------------------------------
- // Batch : ESP1 - Vrac/5 Female/3 Nombre/14
- batch = new SpeciesBatch();
- batch.setId(null);
- batch.setParentBatch(esp1Batch);
- batch.setSpecies(taxon1);
- batch.setComment("ESP1 - Vrac/5 Female/3 Nombre/14");
- batch.setSampleCategoryType(SampleCategoryEnum.sex);
- batch.setSampleCategoryValue(femaleQualitativeValue);
- batch.setSampleCategoryWeight(3f);
- batch.setWeight(null);
- batch.setNumber(14);
-
- assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
-
- // -----------------------------------------------------------------------------
- // 4. Test : ESP2 - Vrac/7
- // \- ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
- // -----------------------------------------------------------------------------
- // batch : "ESP2 - Vrac/7 "
- batch = new SpeciesBatch();
- batch.setParentBatch(null);
- batch.setSpecies(taxon2);
- batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
- batch.setSampleCategoryValue(vracQualitativeValue);
- batch.setSampleCategoryWeight(7f);
-
- assertCreateAndReloadSpeciesBatch(batch, null);
- esp2Batch = batch;
-
- // Batch : ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
- batch = new SpeciesBatch();
- batch.setId(null);
- batch.setParentBatch(esp2Batch);
- batch.setSpecies(taxon2);
- batch.setComment("ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11");
- batch.setSampleCategoryType(SampleCategoryEnum.maturity);
- batch.setSampleCategoryValue(firstMaturityQualitativeValue);
- batch.setSampleCategoryWeight(2f);
- batch.setWeight(1f);
- batch.setNumber(11);
-
- assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
-
- // -----------------------------------------------------------------------------
- // 5. Test save after modifications
- // -----------------------------------------------------------------------------
- // Batch : ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99
- batch.setComment("ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99");
- batch.setSampleCategoryType(SampleCategoryEnum.sex);
- batch.setSampleCategoryValue(unkQualitativeValue);
- batch.setSampleCategoryWeight(1.75f);
- batch.setWeight(1.11f);
- batch.setFishingOperation(fishingOperationWithEmptyBatch);
- batch.setNumber(99);
-
- // Save and reload, then check
- SpeciesBatch savedBatch = service.saveSpeciesBatch(batch);
- assertSpeciesBatch(savedBatch, batch, false);
- SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), savedBatch.getId());
- assertSpeciesBatch(savedBatch, reloadedBatch, true);
-
- // Save batch for later
- frequenciesParentBatch = batch;
-
- // -----------------------------------------------------------------------------
- // 6. Test change species
- // -----------------------------------------------------------------------------
- esp2Batch.setSpecies(taxon1);
- service.changeSpeciesBatchSpecies(esp2Batch.getId(), taxon1);
- assertSpeciesBatch(savedBatch, batch, false);
- reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp2Batch.getId());
- assertSpeciesBatch(esp2Batch, reloadedBatch, true);
-
- // -----------------------------------------------------------------------------
- // 7. Test get all root species
- // -----------------------------------------------------------------------------
- List<SpeciesBatch> rootSpeciesBatch = service.getAllRootSpeciesBatch(fishingOperationWithEmptyBatch.getId());
- assertNotNull(rootSpeciesBatch);
- assertEquals(2, rootSpeciesBatch.size());
- assertNotNull(rootSpeciesBatch.get(0).getChildBatchs());
- assertTrue(rootSpeciesBatch.get(0).getChildBatchs().size() > 0);
- assertNotNull(rootSpeciesBatch.get(1).getChildBatchs());
- assertTrue(rootSpeciesBatch.get(1).getChildBatchs().size() > 0);
-
- // -----------------------------------------------------------------------------
- // 8. Test batch frequency creation
- // -----------------------------------------------------------------------------
-
- List<SpeciesBatchFrequency> frequencies = Lists.newArrayList();
- float lengthStep = 0.5f;
- for (float length = lengthStep; length < lengthStep * 20; length += lengthStep) {
- SpeciesBatchFrequency frequency = new SpeciesBatchFrequency();
- frequency.setLengthStep(length);
- frequency.setNumber((int) (length * 2));
- frequency.setWeight(0.01f * length * 2);
- frequency.setLengthStepCaracteristic(frequencyPMFM);
- frequency.setBatch(frequenciesParentBatch);
- frequency.setComment("comments");
- frequencies.add(frequency);
- }
- List<SpeciesBatchFrequency> createdFrequencies = assertCreateAndReloadSpeciesBatchFrequency(frequencies, frequenciesParentBatch.getId());
-
- // -----------------------------------------------------------------------------
- // 9. Test batch frequency update
- // -----------------------------------------------------------------------------
- // Update some batchs (1cm, 2cm, etc)
- for (SpeciesBatchFrequency speciesBatchFrequency : createdFrequencies) {
- float length = speciesBatchFrequency.getLengthStep();
- if ((float) (int) length == length) {
- speciesBatchFrequency.setNumber(12);
- speciesBatchFrequency.setComment(null);
- }
- }
- // And remove the last item (should be deleted in DB)
- createdFrequencies.remove(createdFrequencies.size()-1);
- List<SpeciesBatchFrequency> savedFrequencies = service.saveSpeciesBatchFrequency(frequenciesParentBatch.getId(), frequencies);
- assertBatchFrequencies(createdFrequencies, savedFrequencies, true);
- }
-
- @Test
- public void deleteSpeciesBatch(/*String id*/) {
- SpeciesBatch esp1Batch;
- SpeciesBatch batch;
- Species taxon1 = species.get(0);
-
- // -----------------------------------------------------------------------------
- // 1. Create two batchs (parent + child), then remove the parent batch
- // -----------------------------------------------------------------------------
- // batch : ESP1 Vrac/5
- batch = new SpeciesBatch();
- batch.setParentBatch(null);
- batch.setFishingOperation(fishingOperationWithEmptyBatch);
- batch.setSpecies(taxon1);
- batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
- batch.setSampleCategoryValue(vracQualitativeValue);
- batch.setSampleCategoryWeight(5f);
- assertCreateAndReloadSpeciesBatch(batch, null);
- esp1Batch = batch;
-
- // batch : ESP1 Vrac/5 Male/2
- batch = new SpeciesBatch();
- batch.setParentBatch(esp1Batch);
- batch.setFishingOperation(fishingOperationWithEmptyBatch);
- batch.setSpecies(taxon1);
- batch.setSampleCategoryType(SampleCategoryEnum.sex);
- batch.setSampleCategoryValue(maleQualitativeValue);
- batch.setSampleCategoryWeight(2f);
- assertCreateAndReloadSpeciesBatch(batch, esp1Batch.getId());
-
- // Try to remove
- service.deleteSpeciesBatch(esp1Batch.getId());
-
- // Check if remove
- try {
- batch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp1Batch.getId());
- assertNull(batch);
- } catch (DataRetrievalFailureException drfe) {
- assertNotNull(drfe);
- }
- }
-
- protected void assertCreateAndReloadSpeciesBatch(SpeciesBatch batch, String parentBatchId) {
- batch.setFishingOperation(fishingOperationWithEmptyBatch);
-
- // Create batch
- SpeciesBatch createdBatch = service.createSpeciesBatch(batch, parentBatchId);
- assertSpeciesBatch(batch, createdBatch, false);
-
- // then reload (for round trip check)
- SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), createdBatch.getId());
- if (parentBatchId == null) {
- assertNull(reloadedBatch.getParentBatch());
- } else {
- assertNotNull(reloadedBatch.getParentBatch());
- assertEquals(parentBatchId, reloadedBatch.getParentBatch().getId());
- }
- assertSpeciesBatch(createdBatch, reloadedBatch, false);
-
- batch.setId(createdBatch.getId());
- }
-
- protected void assertCreateAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
- CatchBatch createdCatchBatch = service.createCatchBatch(catchBatch);
- assertNotNull(createdCatchBatch);
- assertNotNull(createdCatchBatch.getId());
- assertCatchBatch(catchBatch, createdCatchBatch, false);
-
- CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
- assertCatchBatch(createdCatchBatch, reloadedCatchBatch, true);
-
- catchBatch.setId(createdCatchBatch.getId());
- }
-
- protected void assertSaveAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
- CatchBatch savedCatchBatch = service.saveCatchBatch(catchBatch);
- assertNotNull(savedCatchBatch);
- assertNotNull(savedCatchBatch.getId());
- assertCatchBatch(catchBatch, savedCatchBatch, false);
-
- CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
- assertCatchBatch(savedCatchBatch, reloadedCatchBatch, true);
- }
-
- protected void assertCatchBatch(CatchBatch expectedCatchBatch,CatchBatch actualCatchBatch, boolean assertIdEquals) {
- if (expectedCatchBatch == null) {
- assertNull(actualCatchBatch);
- return;
- }
-
- assertNotNull(actualCatchBatch);
- if (assertIdEquals) {
- assertEquals(expectedCatchBatch.getId(), actualCatchBatch.getId());
- }
- assertEquals(expectedCatchBatch.getCatchTotalWeight(), actualCatchBatch.getCatchTotalWeight());
- assertEquals(expectedCatchBatch.getCatchTotalSortedCarousselWeight(), actualCatchBatch.getCatchTotalSortedCarousselWeight());
- assertEquals(expectedCatchBatch.getCatchTotalSortedTremisWeight(), actualCatchBatch.getCatchTotalSortedTremisWeight());
- assertEquals(expectedCatchBatch.getCatchTotalUnsortedWeight(), actualCatchBatch.getCatchTotalUnsortedWeight());
-
- assertEquals(expectedCatchBatch.getSpeciesTotalSampleSortedWeight(), actualCatchBatch.getSpeciesTotalSampleSortedWeight());
- assertEquals(expectedCatchBatch.getSpeciesTotalSortedWeight(), actualCatchBatch.getSpeciesTotalSortedWeight());
- assertEquals(expectedCatchBatch.getSpeciesTotalUnsortedWeight(), actualCatchBatch.getSpeciesTotalUnsortedWeight());
- assertEquals(expectedCatchBatch.getSpeciesTotalInertWeight(), actualCatchBatch.getSpeciesTotalInertWeight());
- assertEquals(expectedCatchBatch.getSpeciesTotalLivingNotItemizedWeight(), actualCatchBatch.getSpeciesTotalLivingNotItemizedWeight());
- }
-
- protected void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
- assertNotNull(actualBatch);
- assertNotNull(actualBatch.getId());
- if (assertIdEquals && expectedBatch.getId() != null) {
- assertEquals(expectedBatch.getId(), actualBatch.getId());
- }
- assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
- assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
- if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
- assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
- actualBatch.getSampleCategoryValue());
- assertEquals(
- ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
- ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
- } else {
- assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
- }
- assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
- assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
- assertEquals(expectedBatch.getComment(), actualBatch.getComment());
-
- // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
- // (Because getSpeciesBatch(id) could not always retrieve the species)
- if (expectedBatch.getSpecies() != null && (
- expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
- || actualBatch.getSpecies() != null)) {
- assertNotNull(actualBatch.getSpecies());
- assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
- }
- }
- protected List<SpeciesBatchFrequency> assertCreateAndReloadSpeciesBatchFrequency(List<SpeciesBatchFrequency> frequencies, String parentBatchId) {
-
- // Create batch
- List<SpeciesBatchFrequency> createdFrequencies = service.saveSpeciesBatchFrequency(parentBatchId, frequencies);
- assertBatchFrequencies(frequencies, createdFrequencies, false);
-
- // then reload (for round trip check)
- List<SpeciesBatchFrequency> reloadedFrequencies = service.getAllSpeciesBatchFrequency(parentBatchId);
- assertBatchFrequencies(createdFrequencies, reloadedFrequencies, true);
-
- return createdFrequencies;
- }
-
- protected void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
- assertNotNull(actualFrequencies);
- assertEquals(expectedFrequencies.size(), actualFrequencies.size());
-
- // Store actual batches into a map, using the length as key
- Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
- for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
- expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
- }
-
- // Store expected batches into a map, using the length as key
- Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
- for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
- assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
- actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
- assertNotNull(speciesBatchFrequency.getId());
- }
-
- for (Float lengthStep : expectedLengthMap.keySet()) {
- SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
- SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
- if (assertIdEquals) {
- assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
- }
- assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
- assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
- assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
- assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
- assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
- //assertNotNull(expectedBatchFrequency.getBatch());
- //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
- }
- }
-
- protected SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
- return getSpeciesBatch(speciesBatchId, service.getAllRootSpeciesBatch(fishingOperationId));
- }
-
- protected SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
- if (speciesBatchs == null) {
- return null;
- }
- for (SpeciesBatch speciesBatch : speciesBatchs) {
- if (speciesBatchId.equals(speciesBatch.getId())) {
- return speciesBatch;
- }
- if (speciesBatch.getChildBatchs() != null) {
- speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
- if (speciesBatch != null) {
- return speciesBatch;
- }
- }
- }
- return null;
- }
-}
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.Cruise;
+import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
+import fr.ifremer.tutti.persistence.entities.referential.Species;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.springframework.dao.DataRetrievalFailureException;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.*;
+
+/**
+ * To test {@link CatchBatchPersistenceService} for write operation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class BatchPersistenceServiceWriteTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.writeDb();
+
+ protected BatchPersistenceService service;
+
+ protected CruisePersistenceService cruiseService;
+
+ protected FishingOperationPersistenceService fishingOperationService;
+
+ protected CatchBatchPersistenceService catchBatchService;
+
+ protected ReferentialPersistenceService referentialService;
+
+ protected Cruise cruise;
+
+ protected FishingOperation fishingOperationNoCatchBatch;
+
+ protected FishingOperation fishingOperationWithEmptyBatch;
+
+ protected CatchBatch catchBacth;
+
+ protected List<Species> species;
+
+ protected Caracteristic sortedUnsortedPMFM;
+
+ protected CaracteristicQualitativeValue horsVracQualitativeValue;
+
+ protected CaracteristicQualitativeValue vracQualitativeValue;
+
+ protected Caracteristic maturityPMFM;
+
+ protected CaracteristicQualitativeValue firstMaturityQualitativeValue;
+
+ protected Caracteristic sexPMFM;
+
+ protected CaracteristicQualitativeValue maleQualitativeValue;
+
+ protected CaracteristicQualitativeValue femaleQualitativeValue;
+
+ protected CaracteristicQualitativeValue unkQualitativeValue;
+
+ protected Caracteristic frequencyPMFM;
+
+ @Before
+ public void setUp() throws Exception {
+ service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
+ cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService();
+ fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
+ catchBatchService = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService();
+ referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService();
+
+ species = referentialService.getAllSpecies();
+ assertNotNull(species);
+ assertTrue(species.size() > 2);
+
+ cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId());
+ cruise.setId(null);
+ Calendar calendar = new GregorianCalendar();
+ cruise.setBeginDate(calendar.getTime());
+ cruise.setYear(calendar.get(Calendar.YEAR));
+ calendar.add(Calendar.MONTH, 1); // add one month
+ cruise.setEndDate(calendar.getTime());
+ cruise = cruiseService.createCruise(cruise);
+
+ // Create a first operation, with no cacth batch : to test CatchBatch insert/update :
+ List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
+ assertNotNull(fishingOperations);
+ assertTrue(fishingOperations.size() > 0);
+ fishingOperationNoCatchBatch = fishingOperations.get(0);
+ fishingOperationNoCatchBatch = fishingOperationService.getFishingOperation(fishingOperationNoCatchBatch.getId());
+ fishingOperationNoCatchBatch.setId(null);
+ fishingOperationNoCatchBatch.setCruise(cruise);
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 1);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationNoCatchBatch.setGearShootingStartDate(calendar.getTime());
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 10);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationNoCatchBatch.setGearShootingEndDate(calendar.getTime());
+ fishingOperationNoCatchBatch = fishingOperationService.createFishingOperation(fishingOperationNoCatchBatch);
+
+ // Create a second operation, with no cacth batch : to test CatchBatch insert/update :
+ fishingOperationWithEmptyBatch = fishingOperations.get(1);
+ fishingOperationWithEmptyBatch = fishingOperationService.getFishingOperation(fishingOperationWithEmptyBatch.getId());
+ fishingOperationWithEmptyBatch.setId(null);
+ fishingOperationWithEmptyBatch.setCruise(cruise);
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 11);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationWithEmptyBatch.setGearShootingStartDate(calendar.getTime());
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 12);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationWithEmptyBatch.setGearShootingEndDate(calendar.getTime());
+ fishingOperationWithEmptyBatch = fishingOperationService.createFishingOperation(fishingOperationWithEmptyBatch);
+
+ catchBacth = new CatchBatch();
+ catchBacth.setFishingOperation(fishingOperationWithEmptyBatch);
+ catchBacth = catchBatchService.createCatchBatch(catchBacth);
+
+ sortedUnsortedPMFM = referentialService.getSortedUnsortedCaracteristic();
+ horsVracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(0);
+ vracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(1);
+ maturityPMFM = referentialService.getMaturityCaracteristic();
+ firstMaturityQualitativeValue = maturityPMFM.getQualitativeValue(0);
+ sexPMFM = referentialService.getSexCaracteristic();
+ maleQualitativeValue = sexPMFM.getQualitativeValue(1);
+ femaleQualitativeValue = sexPMFM.getQualitativeValue(2);
+ unkQualitativeValue = sexPMFM.getQualitativeValue(3);
+
+ List<Caracteristic> cara = referentialService.getAllCaracteristic();
+ for (Caracteristic caracteristic : cara) {
+ if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER
+ && caracteristic.getPrecision() != null
+ && caracteristic.getPrecision() == 0.5f) {
+ frequencyPMFM = caracteristic;
+ break;
+ }
+ }
+ assertNotNull("no numerical PMFM with a precision has been found. Could not define a PMFM for batch frequencies.", frequencyPMFM);
+
+ }
+
+ @Test
+ public void createAndSaveCatchBatch() throws Exception {
+ CatchBatch catchBatch;
+
+ catchBatch = new CatchBatch();
+ catchBatch.setFishingOperation(fishingOperationNoCatchBatch);
+
+ // -----------------------------------------------------------------------------
+ // 1. Test with only mandatory properties
+ // -----------------------------------------------------------------------------
+
+ // Create and reload (test round trip)
+ assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 2. Test with all properties
+ // -----------------------------------------------------------------------------
+ catchBatch.setId(null);
+ // total weight : 100kg
+ catchBatch.setCatchTotalWeight(75f);
+ // Vrac :
+ {
+ // note : poids trie par la balance tremis (thalassa) (init par pupitri)
+ catchBatch.setCatchTotalSortedTremisWeight(50f);
+ // note : poids vrac caroussel (thalassa) (init par pupitri) (vrac trie) ou bien "poids trié fournie par la table de tri (Sum(Si)
+ catchBatch.setCatchTotalSortedCarousselWeight(45f);
+
+ // Species
+ {
+ catchBatch.setSpeciesTotalSortedWeight(12f);
+ catchBatch.setSpeciesTotalSampleSortedWeight(8f);
+ catchBatch.setSpeciesTotalLivingNotItemizedWeight(0.2f);
+ catchBatch.setSpeciesTotalInertWeight(0.1f);
+ }
+ }
+ // Hors Vrac : 10kg
+ {
+ catchBatch.setCatchTotalUnsortedWeight(10f);
+
+ // Species
+ {
+ catchBatch.setSpeciesTotalUnsortedWeight(10f);
+ }
+ }
+ // Rejet : 15kg
+ catchBatch.setCatchTotalRejectedWeight(15f);
+
+ // Create and reload (test round trip)
+ assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 2. Test save after modification
+ // -----------------------------------------------------------------------------
+ catchBatch.setCatchTotalSortedTremisWeight(null);
+ catchBatch.setCatchTotalSortedCarousselWeight(null);
+ catchBatch.setSpeciesTotalSortedWeight(null);
+ catchBatch.setSpeciesTotalSampleSortedWeight(null);
+ catchBatch.setCatchTotalUnsortedWeight(null);
+ catchBatch.setSpeciesTotalUnsortedWeight(null);
+
+ assertSaveAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+ }
+
+ @Test
+ public void createAndSaveSpeciesBatchAndFrequencies() {
+ SpeciesBatch esp1Batch = null;
+ SpeciesBatch esp2Batch = null;
+ SpeciesBatch frequenciesParentBatch = null;
+ SpeciesBatch batch = null;
+ Species taxon1 = species.get(0);
+ Species taxon2 = species.get(1);
+
+ // -----------------------------------------------------------------------------
+ // 1. Test with only mandatory properties
+ // -----------------------------------------------------------------------------
+ // batch : "ESP1 - Vrac/5"
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setFishingOperation(fishingOperationNoCatchBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(5f);
+
+ assertCreateAndReloadSpeciesBatch(batch, null);
+
+ // Save ESP1 batch
+ esp1Batch = batch;
+
+ // -----------------------------------------------------------------------------
+ // 2. Test child "Male/2"
+ // -----------------------------------------------------------------------------
+ // Batch : ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp1Batch);
+ batch.setSpecies(taxon1);
+ batch.setComment("ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(maleQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ batch.setWeight(1f);
+ batch.setNumber(7);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 3. Test child "Female/2"
+ // -----------------------------------------------------------------------------
+ // Batch : ESP1 - Vrac/5 Female/3 Nombre/14
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp1Batch);
+ batch.setSpecies(taxon1);
+ batch.setComment("ESP1 - Vrac/5 Female/3 Nombre/14");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(femaleQualitativeValue);
+ batch.setSampleCategoryWeight(3f);
+ batch.setWeight(null);
+ batch.setNumber(14);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 4. Test : ESP2 - Vrac/7
+ // \- ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
+ // -----------------------------------------------------------------------------
+ // batch : "ESP2 - Vrac/7 "
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setSpecies(taxon2);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(7f);
+
+ assertCreateAndReloadSpeciesBatch(batch, null);
+ esp2Batch = batch;
+
+ // Batch : ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp2Batch);
+ batch.setSpecies(taxon2);
+ batch.setComment("ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11");
+ batch.setSampleCategoryType(SampleCategoryEnum.maturity);
+ batch.setSampleCategoryValue(firstMaturityQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ batch.setWeight(1f);
+ batch.setNumber(11);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 5. Test save after modifications
+ // -----------------------------------------------------------------------------
+ // Batch : ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99
+ batch.setComment("ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(unkQualitativeValue);
+ batch.setSampleCategoryWeight(1.75f);
+ batch.setWeight(1.11f);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setNumber(99);
+
+ // Save and reload, then check
+ SpeciesBatch savedBatch = service.saveSpeciesBatch(batch);
+ assertSpeciesBatch(savedBatch, batch, false);
+ SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), savedBatch.getId());
+ assertSpeciesBatch(savedBatch, reloadedBatch, true);
+
+ // Save batch for later
+ frequenciesParentBatch = batch;
+
+ // -----------------------------------------------------------------------------
+ // 6. Test change species
+ // -----------------------------------------------------------------------------
+ esp2Batch.setSpecies(taxon1);
+ service.changeSpeciesBatchSpecies(esp2Batch.getId(), taxon1);
+ assertSpeciesBatch(savedBatch, batch, false);
+ reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp2Batch.getId());
+ assertSpeciesBatch(esp2Batch, reloadedBatch, true);
+
+ // -----------------------------------------------------------------------------
+ // 7. Test get all root species
+ // -----------------------------------------------------------------------------
+ List<SpeciesBatch> rootSpeciesBatch = service.getAllRootSpeciesBatch(fishingOperationWithEmptyBatch.getId());
+ assertNotNull(rootSpeciesBatch);
+ assertEquals(2, rootSpeciesBatch.size());
+ assertNotNull(rootSpeciesBatch.get(0).getChildBatchs());
+ assertTrue(rootSpeciesBatch.get(0).getChildBatchs().size() > 0);
+ assertNotNull(rootSpeciesBatch.get(1).getChildBatchs());
+ assertTrue(rootSpeciesBatch.get(1).getChildBatchs().size() > 0);
+
+ // -----------------------------------------------------------------------------
+ // 8. Test batch frequency creation
+ // -----------------------------------------------------------------------------
+
+ List<SpeciesBatchFrequency> frequencies = Lists.newArrayList();
+ float lengthStep = 0.5f;
+ for (float length = lengthStep; length < lengthStep * 20; length += lengthStep) {
+ SpeciesBatchFrequency frequency = new SpeciesBatchFrequency();
+ frequency.setLengthStep(length);
+ frequency.setNumber((int) (length * 2));
+ frequency.setWeight(0.01f * length * 2);
+ frequency.setLengthStepCaracteristic(frequencyPMFM);
+ frequency.setBatch(frequenciesParentBatch);
+ frequency.setComment("comments");
+ frequencies.add(frequency);
+ }
+ List<SpeciesBatchFrequency> createdFrequencies = assertCreateAndReloadSpeciesBatchFrequency(frequencies, frequenciesParentBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 9. Test batch frequency update
+ // -----------------------------------------------------------------------------
+ // Update some batchs (1cm, 2cm, etc)
+ for (SpeciesBatchFrequency speciesBatchFrequency : createdFrequencies) {
+ float length = speciesBatchFrequency.getLengthStep();
+ if ((float) (int) length == length) {
+ speciesBatchFrequency.setNumber(12);
+ speciesBatchFrequency.setComment(null);
+ }
+ }
+ // And remove the last item (should be deleted in DB)
+ createdFrequencies.remove(createdFrequencies.size()-1);
+ List<SpeciesBatchFrequency> savedFrequencies = service.saveSpeciesBatchFrequency(frequenciesParentBatch.getId(), frequencies);
+ assertBatchFrequencies(createdFrequencies, savedFrequencies, true);
+ }
+
+ @Test
+ public void deleteSpeciesBatch(/*String id*/) {
+ SpeciesBatch esp1Batch;
+ SpeciesBatch batch;
+ Species taxon1 = species.get(0);
+
+ // -----------------------------------------------------------------------------
+ // 1. Create two batchs (parent + child), then remove the parent batch
+ // -----------------------------------------------------------------------------
+ // batch : ESP1 Vrac/5
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(5f);
+ assertCreateAndReloadSpeciesBatch(batch, null);
+ esp1Batch = batch;
+
+ // batch : ESP1 Vrac/5 Male/2
+ batch = new SpeciesBatch();
+ batch.setParentBatch(esp1Batch);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(maleQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ assertCreateAndReloadSpeciesBatch(batch, esp1Batch.getId());
+
+ // Try to remove
+ service.deleteSpeciesBatch(esp1Batch.getId());
+
+ // Check if remove
+ try {
+ batch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp1Batch.getId());
+ assertNull(batch);
+ } catch (DataRetrievalFailureException drfe) {
+ assertNotNull(drfe);
+ }
+ }
+
+ protected void assertCreateAndReloadSpeciesBatch(SpeciesBatch batch, String parentBatchId) {
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+
+ // Create batch
+ SpeciesBatch createdBatch = service.createSpeciesBatch(batch, parentBatchId);
+ assertSpeciesBatch(batch, createdBatch, false);
+
+ // then reload (for round trip check)
+ SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), createdBatch.getId());
+ if (parentBatchId == null) {
+ assertNull(reloadedBatch.getParentBatch());
+ } else {
+ assertNotNull(reloadedBatch.getParentBatch());
+ assertEquals(parentBatchId, reloadedBatch.getParentBatch().getId());
+ }
+ assertSpeciesBatch(createdBatch, reloadedBatch, false);
+
+ batch.setId(createdBatch.getId());
+ }
+
+ protected void assertCreateAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
+ CatchBatch createdCatchBatch = service.createCatchBatch(catchBatch);
+ assertNotNull(createdCatchBatch);
+ assertNotNull(createdCatchBatch.getId());
+ assertCatchBatch(catchBatch, createdCatchBatch, false);
+
+ CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
+ assertCatchBatch(createdCatchBatch, reloadedCatchBatch, true);
+
+ catchBatch.setId(createdCatchBatch.getId());
+ }
+
+ protected void assertSaveAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
+ CatchBatch savedCatchBatch = service.saveCatchBatch(catchBatch);
+ assertNotNull(savedCatchBatch);
+ assertNotNull(savedCatchBatch.getId());
+ assertCatchBatch(catchBatch, savedCatchBatch, false);
+
+ CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
+ assertCatchBatch(savedCatchBatch, reloadedCatchBatch, true);
+ }
+
+ protected void assertCatchBatch(CatchBatch expectedCatchBatch,CatchBatch actualCatchBatch, boolean assertIdEquals) {
+ if (expectedCatchBatch == null) {
+ assertNull(actualCatchBatch);
+ return;
+ }
+
+ assertNotNull(actualCatchBatch);
+ if (assertIdEquals) {
+ assertEquals(expectedCatchBatch.getId(), actualCatchBatch.getId());
+ }
+ assertEquals(expectedCatchBatch.getCatchTotalWeight(), actualCatchBatch.getCatchTotalWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalSortedCarousselWeight(), actualCatchBatch.getCatchTotalSortedCarousselWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalSortedTremisWeight(), actualCatchBatch.getCatchTotalSortedTremisWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalUnsortedWeight(), actualCatchBatch.getCatchTotalUnsortedWeight());
+
+ assertEquals(expectedCatchBatch.getSpeciesTotalSampleSortedWeight(), actualCatchBatch.getSpeciesTotalSampleSortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalSortedWeight(), actualCatchBatch.getSpeciesTotalSortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalUnsortedWeight(), actualCatchBatch.getSpeciesTotalUnsortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalInertWeight(), actualCatchBatch.getSpeciesTotalInertWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalLivingNotItemizedWeight(), actualCatchBatch.getSpeciesTotalLivingNotItemizedWeight());
+ }
+
+ protected void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
+ assertNotNull(actualBatch);
+ assertNotNull(actualBatch.getId());
+ if (assertIdEquals && expectedBatch.getId() != null) {
+ assertEquals(expectedBatch.getId(), actualBatch.getId());
+ }
+ assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
+ assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
+ if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
+ assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
+ actualBatch.getSampleCategoryValue());
+ assertEquals(
+ ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
+ ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
+ } else {
+ assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
+ }
+ assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
+ assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
+ assertEquals(expectedBatch.getComment(), actualBatch.getComment());
+
+ // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
+ // (Because getSpeciesBatch(id) could not always retrieve the species)
+ if (expectedBatch.getSpecies() != null && (
+ expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
+ || actualBatch.getSpecies() != null)) {
+ assertNotNull(actualBatch.getSpecies());
+ assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
+ }
+ }
+ protected List<SpeciesBatchFrequency> assertCreateAndReloadSpeciesBatchFrequency(List<SpeciesBatchFrequency> frequencies, String parentBatchId) {
+
+ // Create batch
+ List<SpeciesBatchFrequency> createdFrequencies = service.saveSpeciesBatchFrequency(parentBatchId, frequencies);
+ assertBatchFrequencies(frequencies, createdFrequencies, false);
+
+ // then reload (for round trip check)
+ List<SpeciesBatchFrequency> reloadedFrequencies = service.getAllSpeciesBatchFrequency(parentBatchId);
+ assertBatchFrequencies(createdFrequencies, reloadedFrequencies, true);
+
+ return createdFrequencies;
+ }
+
+ protected void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
+ assertNotNull(actualFrequencies);
+ assertEquals(expectedFrequencies.size(), actualFrequencies.size());
+
+ // Store actual batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
+ expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ }
+
+ // Store expected batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
+ assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
+ actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ assertNotNull(speciesBatchFrequency.getId());
+ }
+
+ for (Float lengthStep : expectedLengthMap.keySet()) {
+ SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
+ SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
+ if (assertIdEquals) {
+ assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
+ }
+ assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
+ assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
+ assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
+ assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
+ assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
+ //assertNotNull(expectedBatchFrequency.getBatch());
+ //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
+ }
+ }
+
+ protected SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
+ return getSpeciesBatch(speciesBatchId, service.getAllRootSpeciesBatch(fishingOperationId));
+ }
+
+ protected SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
+ if (speciesBatchs == null) {
+ return null;
+ }
+ for (SpeciesBatch speciesBatch : speciesBatchs) {
+ if (speciesBatchId.equals(speciesBatch.getId())) {
+ return speciesBatch;
+ }
+ if (speciesBatch.getChildBatchs() != null) {
+ speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
+ if (speciesBatch != null) {
+ return speciesBatch;
+ }
+ }
+ }
+ return null;
+ }
+}
Property changes on: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -631,82 +631,6 @@
updateTable(TuttiTable.AGGREGATION_LEVEL, internalDb, internalConnection, externalConnection, fromDate, 1, 0);
}
- @Test
- public void synchronize() throws IOException, SQLException {
-
- createInternalConnection();
-
- TuttiDatabaseMetadata internalDb =
- helper.loadDatabaseMetadata(internalConnection, dialect);
- Assert.assertNotNull(internalDb);
-
- createExternalDb();
-
- // synchronize from main db to empty db
-
- ReferentialSynchronizeResult result =
- helper.synchronize(externalConnectionProperties,
- localConnectionProperties,
- dialect);
-
- // same referentiel in both db
- Assert.assertNotNull(result);
- Assert.assertNull(result.getError());
-
- DatabaseSynchroFixtures fixturesExternal;
- DatabaseSynchroFixtures fixturesInternal;
-
- fixturesInternal = new DatabaseSynchroFixtures(
- helper, internalDb, internalConnection);
- fixturesExternal = new DatabaseSynchroFixtures(
- helper, internalDb, externalConnection);
-
- for (TuttiTable tuttiTable : TuttiTable.values()) {
- String tableName = tuttiTable.name();
- int nbInserts = result.getNbInserts(tableName);
- int nbUpdates = result.getNbUpdates(tableName);
- int expected = fixturesInternal.count(tuttiTable);
- Assert.assertEquals(String.format("Table %s Should found %s inserts, but was only %s", tableName, expected, nbInserts), expected, nbInserts, 0);
- Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, 0, nbUpdates), 0, nbUpdates, 0);
- Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, fixturesInternal.count(tuttiTable), nbUpdates), fixturesInternal.count(tuttiTable), fixturesExternal.count(tuttiTable), 0);
- }
-
- // add a new status
- internalConnection.prepareStatement("INSERT INTO STATUS(CODE, NAME) VALUES (4, 'NEW')").executeUpdate();
-
- // add a new aggregation_level
- internalConnection.prepareStatement("INSERT INTO AGGREGATION_LEVEL (ID, NAME, RANK_ORDER, UPDATE_DATE) VALUES (-1000, 'NAME', -1000, NULL)").executeUpdate();
-
- // update a unit
- PreparedStatement preparedStatement = internalConnection.prepareStatement("UPDATE UNIT SET SYMBOL = 'Auncun un?', UPDATE_DATE=? WHERE ID=1");
- preparedStatement.setDate(1, new java.sql.Date(System.currentTimeMillis()));
- preparedStatement.executeUpdate();
-
- internalConnection.commit();
-
- fixturesInternal = new DatabaseSynchroFixtures(
- helper, internalDb, internalConnection);
-
- result = helper.synchronize(externalConnectionProperties,
- localConnectionProperties,
- dialect);
- Assert.assertNotNull(result);
- Assert.assertNull(result.getError());
-
- fixturesExternal = new DatabaseSynchroFixtures(
- helper, internalDb, externalConnection);
-
- for (TuttiTable tuttiTable : TuttiTable.values()) {
- String tableName = tuttiTable.name();
-
- int internalCount = fixturesInternal.count(tuttiTable);
- int externalCount = fixturesExternal.count(tuttiTable);
-
- Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, internalCount, externalCount), internalCount, externalCount, 0);
- }
-
- }
-
protected ResultSet getDataToUpdate(TuttiTable tuttiTable,
TuttiDatabaseMetadata db,
Connection connection,
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -25,6 +25,7 @@
*/
import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.ProgressionModel;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import fr.ifremer.tutti.persistence.service.TuttiPersistenceServiceLocator;
import org.hibernate.dialect.Dialect;
@@ -37,6 +38,12 @@
import org.junit.rules.TestName;
import org.springframework.jdbc.support.JdbcUtils;
+import javax.swing.JDialog;
+import javax.swing.JProgressBar;
+import java.awt.Frame;
+import java.awt.GraphicsEnvironment;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@@ -69,6 +76,8 @@
protected ReferentialSynchronizeHelper helper;
+ protected JDialog dialog;
+
@Before
public void setUp() throws Exception {
@@ -91,6 +100,9 @@
@After
public void tearDown() throws Exception {
+ if (dialog != null) {
+ dialog.setVisible(false);
+ }
service = null;
remoteConnectionProperties = null;
dialect = null;
@@ -107,7 +119,6 @@
DatabaseSynchroFixtures fixturesRemote;
DatabaseSynchroFixtures fixturesLocal;
- ReferentialSynchronizeResult result;
// add some stuff on remote db
@@ -127,12 +138,69 @@
fixturesRemote = new DatabaseSynchroFixtures(
helper, remoteSchema, remoteConnection);
- result = service.synchronize(remoteConnectionProperties);
+ fixturesLocal = new DatabaseSynchroFixtures(
+ helper, remoteSchema, localConnection);
- // same referentiel in both db
+ ReferentialSynchronizeResult result =
+ new ReferentialSynchronizeResult();
+
+
+ dialog = createProgressBar(result);
+
+ service.prepare(remoteConnectionProperties, result);
+
Assert.assertNotNull(result);
Assert.assertNull(result.getError());
+ Assert.assertTrue(result.isSuccess());
+ // on entities, only updates in table is with no update_date
+ for (TuttiTable tuttiTable : TuttiTable.getEntityTables()) {
+ String tableName = tuttiTable.name();
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int nbRows = result.getNbRows(tableName);
+ int expectedRows = 0;
+ TuttiTableMetadata table = remoteSchema.getTable(tableName);
+ if (!table.isWithUpdateDateColumn()) {
+ // updates everything
+ expectedRows = nbRemote;
+ }
+
+ switch (tuttiTable) {
+ case STATUS:
+ nbLocal++;
+ break;
+
+ case UNIT:
+ expectedRows = 1;
+ break;
+
+ case AGGREGATION_LEVEL:
+ nbLocal++;
+ expectedRows = 1;
+ break;
+ }
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows to treat, but was only %s", tableName, expectedRows, nbRows), expectedRows, nbRows, 0);
+ }
+
+ // on associations, only inserts
+ for (TuttiTable tuttiTable : TuttiTable.getAssociationTables()) {
+ String tableName = tuttiTable.name();
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int nbRows = result.getNbRows(tableName);
+ int expectedRows = nbRemote;
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows to treat, but was only %s", tableName, expectedRows, nbRows), expectedRows, nbRows, 0);
+ }
+
+ service.synchronize(remoteConnectionProperties, result);
+
+ Assert.assertEquals(result.getTotalRows(), result.getProgressionModel().getTotal());
+ Assert.assertEquals(result.getProgressionModel().getTotal(), result.getProgressionModel().getCurrent());
+ Assert.assertEquals(1.0, result.getProgressionModel().getRate(), 0.01);
+
fixturesLocal = new DatabaseSynchroFixtures(
helper, remoteSchema, localConnection);
@@ -187,6 +255,45 @@
Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, expectedUpdates, nbUpdates), expectedUpdates, nbUpdates, 0);
Assert.assertEquals(String.format("Table %s Should found %s rows treated, but was only %s", tableName, expectedRows, nbInserts + nbUpdates), expectedRows, nbInserts + nbUpdates, 0);
}
+ }
+ public static JDialog createProgressBar(ReferentialSynchronizeResult result) {
+
+ JDialog dialog;
+ if (GraphicsEnvironment.isHeadless()) {
+ dialog = null;
+ } else {
+ dialog = new JDialog((Frame) null,
+ "synchronisation " + result.getLocalUrl() + " from " + result.getRemoteUrl(),
+ false);
+ dialog.setSize(600, 400);
+ final JProgressBar progressBar = new JProgressBar();
+ progressBar.setStringPainted(true);
+ progressBar.setIndeterminate(false);
+ ProgressionModel progressionModel = result.getProgressionModel();
+ progressionModel.addPropertyChangeListener(ProgressionModel.PROPERTY_MESSAGE, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ progressBar.setString((String) evt.getNewValue());
+ }
+ });
+ progressionModel.addPropertyChangeListener(ProgressionModel.PROPERTY_TOTAL, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ progressBar.setMinimum(0);
+ progressBar.setMaximum((Integer) evt.getNewValue());
+ }
+ });
+ progressionModel.addPropertyChangeListener(ProgressionModel.PROPERTY_CURRENT, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ progressBar.setValue((Integer) evt.getNewValue());
+
+ }
+ });
+ dialog.add(progressBar);
+ dialog.setVisible(true);
+ }
+ return dialog;
}
}
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -37,6 +37,8 @@
import org.junit.rules.TestName;
import org.springframework.jdbc.support.JdbcUtils;
+import javax.swing.JDialog;
+import java.awt.GraphicsEnvironment;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
@@ -67,6 +69,8 @@
protected ReferentialSynchronizeHelper helper;
+ protected JDialog dialog;
+
@Before
public void setUp() throws Exception {
@@ -89,6 +93,9 @@
@After
public void tearDown() throws Exception {
+ if (dialog!=null) {
+ dialog.setVisible(false);
+ }
service = null;
remoteConnectionProperties = null;
dialect = null;
@@ -105,17 +112,53 @@
DatabaseSynchroFixtures fixturesRemote;
DatabaseSynchroFixtures fixturesLocal;
- ReferentialSynchronizeResult result;
fixturesRemote = new DatabaseSynchroFixtures(
helper, remoteSchema, remoteConnection);
- result = service.synchronize(remoteConnectionProperties);
+ fixturesLocal = new DatabaseSynchroFixtures(
+ helper, remoteSchema, localConnection);
- // same referentiel in both db
+ ReferentialSynchronizeResult result = new ReferentialSynchronizeResult();
+
+ dialog = ReferentialSynchronizeServiceImplTest.createProgressBar(result);
+
+ service.prepare(remoteConnectionProperties, result);
+
Assert.assertNotNull(result);
Assert.assertNull(result.getError());
+ Assert.assertTrue(result.isSuccess());
+ // on entities, only updates in table is with no update_date
+ for (TuttiTable tuttiTable : TuttiTable.getEntityTables()) {
+ String tableName = tuttiTable.name();
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int nbRows = result.getNbRows(tableName);
+ int expectedRows = 0;
+ TuttiTableMetadata table = remoteSchema.getTable(tableName);
+ if (!table.isWithUpdateDateColumn()) {
+ // updates everything
+ expectedRows = nbRemote;
+ }
+
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows to treat, but was only %s", tableName, expectedRows, nbRows), expectedRows, nbRows, 0);
+ }
+
+ // on associations, only inserts
+ for (TuttiTable tuttiTable : TuttiTable.getAssociationTables()) {
+ String tableName = tuttiTable.name();
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int nbRows = result.getNbRows(tableName);
+ int expectedRows = nbRemote;
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows to treat, but was only %s", tableName, expectedRows, nbRows), expectedRows, nbRows, 0);
+ }
+
+ service.synchronize(remoteConnectionProperties, result);
+
fixturesLocal = new DatabaseSynchroFixtures(
helper, remoteSchema, localConnection);
1
0
r413 - in trunk/tutti-persistence/src: main/java/fr/ifremer/tutti/persistence/service main/java/fr/ifremer/tutti/persistence/service/measure main/resources main/resources/i18n test/java/fr/ifremer/tutti/persistence/service
by blavenier@users.forge.codelutin.com 14 Feb '13
by blavenier@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: blavenier
Date: 2013-02-14 16:27:16 +0100 (Thu, 14 Feb 2013)
New Revision: 413
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/413
Log:
Fix :
- saveBatchFrequencies now delete extra batch
- store weights for 'inert' and 'livingNotSorted'
Add :
- ReferentialPersistenceService.getSampleCategoryIds()
Improve :
- Merge CatchBatchPersistenceService and SpeciesBatchPersistenceService into BatchPersistenceService
- batch management now use adagio implementation CatchBatchExtendDao
Added:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
Removed:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java
Modified:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/measure/MeasurementPersistenceHelper.java
trunk/tutti-persistence/src/main/resources/applicationContext-service-tutti.xml
trunk/tutti-persistence/src/main/resources/i18n/tutti-persistence_fr_FR.properties
trunk/tutti-persistence/src/main/resources/queries-override.hbm.xml
trunk/tutti-persistence/src/main/resources/tutti-db-conf.properties
trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -38,6 +38,7 @@
import java.io.Serializable;
import java.util.Iterator;
+import java.util.List;
/**
* TODO
@@ -123,6 +124,13 @@
return result;
}
+ protected <T> List<T> queryList2Typed(String queryName, Object... params) {
+
+ Query query = createQuery(queryName, params);
+ List result = query.list();
+ return result;
+ }
+
protected Query createQuery(String queryName, Object... params) {
Query query = getCurrentSession().getNamedQuery(queryName);
Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -0,0 +1,8 @@
+package fr.ifremer.tutti.persistence.service;
+
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional(readOnly = true)
+public interface BatchPersistenceService extends CatchBatchPersistenceService, SpeciesBatchPersistenceService{
+
+}
Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -0,0 +1,1297 @@
+package fr.ifremer.tutti.persistence.service;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.Serializable;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.annotation.Resource;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.FlushMode;
+import org.hibernate.type.IntegerType;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.DataRetrievalFailureException;
+import org.springframework.stereotype.Service;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+import fr.ifremer.adagio.core.dao.data.batch.Batch;
+import fr.ifremer.adagio.core.dao.data.batch.CatchBatchExtendDao;
+import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
+import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
+import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationError;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidator;
+import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
+import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
+import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
+import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
+import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
+import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
+import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
+import fr.ifremer.tutti.persistence.entities.referential.Species;
+import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
+
+@Service("batchPersistenceService")
+public class BatchPersistenceServiceImpl
+ extends AbstractPersistenceService implements BatchPersistenceService, CatchBatchValidator
+ {
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(BatchPersistenceServiceImpl.class);
+
+ @Resource(name = "referentialPersistenceService")
+ protected ReferentialPersistenceService referentialService;
+
+ @Resource(name = "denormalizedBatchDao")
+ protected DenormalizedBatchDao denormalizedBatchDao;
+
+ @Resource(name = "sortingBatchDao")
+ protected SortingBatchDao sortingBatchDao;
+
+ @Resource(name = "catchBatchDao")
+ protected CatchBatchExtendDao catchBatchDao;
+
+ @Resource(name = "measurementPersistenceHelper")
+ protected MeasurementPersistenceHelper measurementHelper;
+
+ @Override
+ public void init() {
+ super.init();
+ catchBatchDao.registerCatchBatchValidator(this);
+ }
+
+ @Override
+ public void close() {
+ catchBatchDao.unregisterCatchBatchValidator(this);
+ super.close();
+ }
+
+ @Override
+ public boolean isEnable(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+ // Apply validation only on catch batch for fishingOperation
+ return (catchBatch.getFishingOperation() != null);
+ }
+
+ @Override
+ public List<CatchBatchValidationError> validate(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+ List<CatchBatchValidationError> errors = Lists.newArrayList();
+ validate(catchBatch.getChildBatchs(), errors, 1);
+ return errors;
+ }
+
+ @Override
+ public CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) {
+ Preconditions.checkNotNull(fishingOperationId);
+
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
+
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch source;
+ try {
+ source = catchBatchDao.loadFullTree(catchBatchId, true, true);
+ } catch (CatchBatchValidationException e) {
+ throw new DataRetrievalFailureException("Invalid batch tree structure, for fishing operation id=" + fishingOperationId, e);
+ }
+
+ CatchBatch result = new CatchBatch();
+ result.setId(source.getId().toString());
+ result.setCatchTotalWeight(source.getWeight());
+
+ // Vrac
+ SortingBatch vracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID);
+ result.setCatchTotalSortedCarousselWeight(vracBatch.getWeight());
+ result.setCatchTotalSortedTremisWeight(vracBatch.getWeightBeforeSampling());
+ {
+ // Species
+ SortingBatch speciesBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ result.setSpeciesTotalSampleSortedWeight(speciesBatch.getWeight());
+ result.setSpeciesTotalSortedWeight(speciesBatch.getWeightBeforeSampling());
+
+ {
+ // Inert
+ SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
+ "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
+ result.setSpeciesTotalInertWeight(inertBatch.getWeight());
+
+ // Alive no itemized
+ SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
+ "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
+ result.setSpeciesTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight());
+ }
+
+ // TODO : Benthos, Plancton...
+ }
+
+ // Hors Vrac
+ SortingBatch horsVracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID);
+ result.setCatchTotalUnsortedWeight(horsVracBatch.getWeight());
+ {
+ // Species
+ SortingBatch speciesBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ result.setSpeciesTotalUnsortedWeight(speciesBatch.getWeight());
+
+ // TODO : Benthos, Plancton...
+ }
+
+ // Non trié
+ SortingBatch unsortedBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID);
+ result.setCatchTotalRejectedWeight(unsortedBatch.getWeight());
+
+ return result;
+ }
+
+ @Override
+
+ public CatchBatch createCatchBatch(CatchBatch bean) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkArgument(bean.getId() == null);
+ Preconditions.checkNotNull(bean.getFishingOperation());
+ Preconditions.checkNotNull(bean.getFishingOperation().getId());
+
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = fr.ifremer.adagio.core.dao.data.batch.CatchBatch.Factory.newInstance();
+ beanToEntity(bean, catchBatch, true);
+ catchBatch = catchBatchDao.create(catchBatch);
+ bean.setId(String.valueOf(catchBatch.getId()));
+
+ // Link to fishing operation
+ getCurrentSession().flush();
+ Integer fishingOperationId = Integer.valueOf(bean.getFishingOperation().getId());
+ int rowUpdated = queryUpdate("updateFishingOperationCatchBatch",
+ "fishingOperationId", IntegerType.INSTANCE, fishingOperationId,
+ "catchBatchId", IntegerType.INSTANCE, catchBatch.getId());
+ if (rowUpdated == 0) {
+ throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found.");
+ }
+
+ return bean;
+ }
+
+ @Override
+ @CacheEvict(value = "batchTree", key="#bean.fishingOperation.id")
+ public CatchBatch saveCatchBatch(CatchBatch bean) {
+
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkNotNull(bean.getId());
+
+ getCurrentSession().enableFetchProfile("batch-with-childs");
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(Integer.valueOf(bean.getId()));
+ if (catchBatch == null) {
+ throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId());
+ }
+
+ beanToEntity(bean, catchBatch, true);
+ catchBatchDao.update(catchBatch);
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) {
+
+ // Load batch tree
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ List<SpeciesBatch> result = new ArrayList<SpeciesBatch>();
+
+ // Vrac / Species
+ SortingBatch vracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ for (Iterator<Batch> iterator = vracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+
+ // evict some special batches : Life (or Biota) and Inert
+ if (source.getReferenceTaxon() != null
+ && enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) == false
+ && enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId()) == false) {
+ SpeciesBatch target = new SpeciesBatch();
+
+ entityToBean(source, target);
+ result.add(target);
+ }
+ }
+
+ // Hors-Vrac / Species
+ SortingBatch horsVracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ for (Iterator<Batch> iterator = horsVracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+
+ SpeciesBatch target = new SpeciesBatch();
+
+ entityToBean(source, target);
+ result.add(target);
+ }
+
+ return result;
+ }
+
+ protected SpeciesBatch entityToBean(SortingBatch source, SpeciesBatch target) {
+
+ target.setId(source.getId().toString());
+
+ // Individual count
+ target.setNumber(source.getIndividualCount());
+
+ // Convert database weight (and sampling ratio) into UI weight and sampleCategoryWeight
+ if (source.getWeight() != null && source.getWeightBeforeSampling() == null) {
+ target.setSampleCategoryWeight(source.getWeight());
+ }
+ else {
+ target.setWeight(source.getWeight());
+ target.setSampleCategoryWeight(source.getWeightBeforeSampling());
+ }
+
+ // Comments
+ target.setComment(source.getComments());
+
+ // Sample category type (only one is applied)
+ SortingMeasurement sm = null;
+ if (source.getSortingMeasurements().size() == 1) {
+ sm = source.getSortingMeasurements().iterator().next();
+ }
+ else if (source.getReferenceTaxon() != null && source.getReferenceTaxon().getId() != null){
+ sm = measurementHelper.getInheritedSortingMeasurement(source, enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+ if (sm != null) {
+ SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(sm.getPmfm().getId());
+ if (sampleCategory != null) {
+ setSampleCategoryQualitative(target, sm.getPmfm().getId(), sm.getNumericalValue(), sm.getAlphanumericalValue(), sm.getQualitativeValue().getId());
+ }
+ }
+
+ // Species
+ Integer referenceTaxonId = source.getInheritedReferenceTaxonId();
+ if (referenceTaxonId == null && source.getReferenceTaxon() != null) {
+ referenceTaxonId = source.getReferenceTaxon().getId();
+ }
+ if (referenceTaxonId != null) {
+ // TODO : add cache on getSpeciesByReferenceTaxonId
+ Species species = referentialService.getSpeciesByReferenceTaxonId(referenceTaxonId);
+ target.setSpecies(species);
+ }
+
+ if (target.getSampleCategoryType() != null && source.getChildBatchs().size() > 0) {
+ List<SpeciesBatch> targetChilds = Lists.newArrayList();
+ for (Iterator<Batch> iterator = source.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch sourceChild = (SortingBatch) iterator.next();
+ SpeciesBatch targetChild = new SpeciesBatch();
+ entityToBean(sourceChild, targetChild);
+ if (targetChild.getSampleCategoryValue() != null) {
+ targetChilds.add(targetChild);
+ targetChild.setParentBatch(target);
+ }
+ }
+ target.setChildBatchs(targetChilds);
+ }
+
+ return target;
+ }
+
+ @Override
+ public SpeciesBatch createSpeciesBatch(SpeciesBatch bean,
+ String parentBatchId) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkArgument(bean.getId() == null);
+ Preconditions.checkNotNull(bean.getSpecies());
+ Preconditions.checkNotNull(bean.getSpecies().getId());
+ Preconditions.checkNotNull(bean.getFishingOperation());
+ Preconditions.checkNotNull(bean.getFishingOperation().getId());
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ // Load full batch tree
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(bean.getFishingOperation().getId()));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ SortingBatch batch = SortingBatch.Factory.newInstance();
+ beanToEntity(bean, batch, parentBatchId, catchBatch, true);
+ batch = sortingBatchDao.create(batch);
+
+ bean.setId(String.valueOf(batch.getId()));
+
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkNotNull(bean.getId());
+
+ // Load full batch tree
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(bean.getId()));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ SortingBatch batch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(bean.getId()));
+ String parentBatchId = null;
+ if (bean.getParentBatch() != null) {
+ parentBatchId = bean.getParentBatch().getId();
+ }
+ beanToEntity(bean, batch, parentBatchId, catchBatch, true);
+ sortingBatchDao.update(batch);
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public void deleteSpeciesBatch(String id) {
+ Preconditions.checkNotNull(id);
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ catchBatchDao.removeWithChildren(Integer.valueOf(id));
+
+ getCurrentSession().flush();
+ }
+
+ public void deleteSpeciesSubBatch(String id) {
+ deleteSpeciesBatch(id);
+ }
+
+ public void changeSpeciesBatchSpecies(String batchId, Species species) {
+ Preconditions.checkNotNull(batchId);
+ Preconditions.checkNotNull(species);
+ Preconditions.checkNotNull(species.getReferenceTaxonId());
+
+ if (log.isDebugEnabled()) {
+ log.debug("Changing species for batch id=" + batchId);
+ }
+
+ int rowUpdated = queryUpdate("updateBatchSpecies",
+ "batchId", IntegerType.INSTANCE, Integer.valueOf(batchId),
+ "referenceTaxonId", IntegerType.INSTANCE, species.getReferenceTaxonId());
+ Preconditions.checkArgument(rowUpdated == 1, "Unable to update operation, to be linked with catch batch.");
+ }
+
+ public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
+ String speciesBatchId) {
+ List<SpeciesBatchFrequency> results = Lists.newArrayList();
+
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ if (catchBatchId == null) {
+ return results;
+ }
+
+ SortingBatch sortingBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
+
+ for (Iterator<Batch> iterator = sortingBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+ SpeciesBatchFrequency target = new SpeciesBatchFrequency();
+
+ entityToBean(source, target);
+ results.add(target);
+ }
+ return results;
+ }
+
+ protected void entityToBean(SortingBatch source, SpeciesBatchFrequency target) {
+
+ target.setId(source.getId().toString());
+
+ target.setNumber(source.getIndividualCount());
+ target.setWeight(source.getWeight());
+ target.setComment(source.getComments());
+
+ // Length step category
+ if (source.getSortingMeasurements().size() == 1) {
+ SortingMeasurement sm = source.getSortingMeasurements().iterator().next();
+ if (sm.getPmfm() != null && sm.getPmfm().getId() != null) {
+ Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(sm.getPmfm().getId());
+ target.setLengthStepCaracteristic(lengthStepCaracteristic);
+ }
+
+ // Length
+ target.setLengthStep(sm.getNumericalValue());
+ }
+ }
+
+ public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(
+ String speciesBatchId, List<SpeciesBatchFrequency> frequencies) {
+ Preconditions.checkNotNull(speciesBatchId);
+ Preconditions.checkNotNull(frequencies);
+
+ if (frequencies.size() == 0) {
+ return frequencies;
+ }
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ if (catchBatch == null) {
+ return frequencies;
+ }
+
+ // Retrieve parent
+ SortingBatch parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
+
+ // Remember child ids, to remove unchanged item (see at bottom in this method)
+ List<Integer> notUpdatedChildIds = Lists.newArrayList();
+ for (Iterator<Batch> iterator = parentBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch sortingBatch = (SortingBatch) iterator.next();
+ notUpdatedChildIds.add(sortingBatch.getId());
+ }
+
+ short rankOrder = 0;
+ String pmfmId = null;
+ List<SortingBatch> batchsToUpdate = Lists.newArrayList();
+ for (SpeciesBatchFrequency source : frequencies) {
+ rankOrder++;
+
+ // Check that all frequencies have the same length PMFM
+ if (pmfmId == null) {
+ source.getLengthStepCaracteristic().getId();
+ } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) {
+ throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic");
+ }
+
+ // Not existing batch
+ SortingBatch target = null;
+ if (source.getId() == null) {
+ target = SortingBatch.Factory.newInstance();
+
+ // Fill the sorting batch from the source
+ beanToEntity(source, target, parentBatch, rankOrder, true);
+
+ // Create the targeted batch, then update the source id
+ sortingBatchDao.create(target);
+ source.setId(target.getId().toString());
+ }
+
+ // Existing batch
+ else {
+ target = sortingBatchDao.load(Integer.valueOf(source.getId()));
+
+ // Fill the sorting batch from the source
+ beanToEntity(source, target, parentBatch, rankOrder, true);
+
+ // Add the batch into a list (will be update later, using this list)
+ batchsToUpdate.add(target);
+
+ notUpdatedChildIds.remove(target.getId());
+ }
+ }
+
+ // If some batchs need to be update, do it
+ if (batchsToUpdate.size() > 0) {
+ sortingBatchDao.update(batchsToUpdate);
+ }
+
+ if (notUpdatedChildIds.size() > 0) {
+ for (Iterator<Integer> iterator = notUpdatedChildIds.iterator(); iterator.hasNext();) {
+ Integer batchId = iterator.next();
+ catchBatchDao.removeWithChildren(batchId);
+ }
+ }
+
+ getCurrentSession().flush();
+
+ return frequencies;
+ }
+
+ // ------------------------------------------------------------------------//
+ // -- Internal methods --//
+ // ------------------------------------------------------------------------//
+
+ protected void validate(Collection<Batch> batchs, List<CatchBatchValidationError> errors, int treeLevel) {
+
+ List<Integer> expectedPmfms = null;
+ boolean expectedReferenceTaxon = false;
+ // First tree level : should have pmfm SORTED (Vrac, Hors Vrac, Non trié)
+ if (treeLevel == 1) {
+ expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+ // Second tree level : should have pmfm SORTING_TYPE (Species, Benthos...)
+ else if (treeLevel == 2) {
+ expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTING_TYPE);
+ }
+ else if (treeLevel == 3) {
+ expectedReferenceTaxon = true;
+ }
+ else if (treeLevel > 3) {
+ expectedPmfms = referentialService.getSampleCategoryIds();
+ expectedPmfms.remove(enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+
+ // First level : should be only PMFM=SORTED
+ for (Iterator<Batch> iterator = batchs.iterator(); iterator.hasNext();) {
+ SortingBatch batch = (SortingBatch) iterator.next();
+ boolean batchHasError = false;
+
+ // For all sorting measurements
+ if (batch.getSortingMeasurements() != null && batch.getSortingMeasurements().size() > 0) {
+ for (Iterator<SortingMeasurement> iterator2 = batch.getSortingMeasurements().iterator(); iterator2.hasNext();) {
+ SortingMeasurement sm = iterator2.next();
+ Integer pmfmId = sm.getPmfm().getId();
+ if (expectedReferenceTaxon) {
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.onlyTaxonButPmfmFound",
+ _("tutti.persistence.batch.validation.onlyTaxonButPmfmFound", batch.getId(), pmfmId),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+ else if (expectedPmfms.contains(pmfmId) == false) {
+ if (sm.getNumericalValue() == null || batch.getChildBatchs().size() > 0) {
+ batchHasError = true;
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.pmfmNotFound",
+ _("tutti.persistence.batch.validation.pmfmNotFound",
+ batch.getId(), Arrays.toString(expectedPmfms.toArray()), pmfmId),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+ }
+ }
+ }
+ else if (expectedPmfms != null && expectedPmfms.size() > 0){
+ batchHasError = true;
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.pmfmNotFound",
+ _("tutti.persistence.batch.validation.pmfmNotFound",
+ batch.getId(), Arrays.toString(expectedPmfms.toArray()), "null"),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+
+ if (!batchHasError && expectedReferenceTaxon == true && batch.getReferenceTaxon() == null) {
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.referenceTaxonNotFound",
+ _("tutti.persistence.batch.validation.referenceTaxonNotFound", batch.getId()),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+
+ if (!batchHasError) {
+ validate(batch.getChildBatchs(), errors, treeLevel+1);
+ }
+ }
+ }
+
+ protected void beanToEntity(SpeciesBatch source,
+ SortingBatch target,
+ String parentBatchId,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch,
+ boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // If parent and root need to be set
+ if (target.getId() == null
+ || target.getRootBatch() == null
+ || (target.getParentBatch() != null && !target.getParentBatch().getId().toString().equals(parentBatchId))) {
+ setBatchParents(source, target, parentBatchId, catchBatch);
+ }
+
+ // RankOrder (initialize once, at creation)
+ if (target.getRankOrder() == null) {
+ // Start rank order at 3, because of special batches 'Biota' and 'Inert'
+ short rankOrder = (short) 3;
+ if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) {
+ // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?)
+ rankOrder += (short) source.getParentBatch().getChildBatchs().size();
+ }
+ target.setRankOrder(rankOrder);
+ }
+
+ // Force subgroup count to '1', as Allegro
+ target.setSubgroupCount(1f);
+
+ // Weight or SampleCategoryWeight
+ if (copyIfNull && source.getWeight() == null && source.getSampleCategoryWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getSampleCategoryWeight() != null && source.getWeight() == null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sampling Ratio
+ if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) {
+ String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight();
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight());
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sorting measurement
+ if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) {
+ Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
+ // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch)
+ if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
+ SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId,
+ source.getSampleCategoryType(), source.getSampleCategoryValue());
+ notChangedSortingMeasurements.remove(sortingMeasurement);
+ }
+ }
+
+ // Individual count
+ if (copyIfNull && source.getNumber() == null) {
+ target.setIndividualCount(null);
+ } else if (source.getNumber() != null) {
+ target.setIndividualCount(source.getNumber());
+ }
+
+ // Species
+ if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) {
+ target.setReferenceTaxon(null);
+ } else if (source.getSpecies() != null && parentBatchId == null) {
+ ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId());
+ target.setReferenceTaxon(referenceTaxon);
+ }
+
+ // QualityFlag
+ if (source.isSpeciesToConfirm()) {
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL));
+ } else {
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ }
+
+ // Comments
+ if (copyIfNull && source.getComment() == null) {
+ target.setComments(null);
+ } else if (source.getComment() != null) {
+ target.setComments(source.getComment());
+ }
+
+ // Exhaustive inventory (always true under a species batch)
+ target.setExhaustiveInventory(true);
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ public void setBatchParents(SpeciesBatch source, SortingBatch target, String parentBatchIdStr,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+
+ Preconditions.checkNotNull(target);
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Load existing parent and root
+ SortingBatch parentBatch = null;
+ if (parentBatchIdStr != null) {
+ parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(parentBatchIdStr));
+ }
+
+ // Or retrieve parent batch, from pmfm id
+ else {
+ // Retrieve category type
+ Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
+ if (pmfmId == null || !pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
+ throw new DataIntegrityViolationException(MessageFormat.format(
+ "A species batch with no parent should have a sampleCategoryType {0} (PMFM.ID={1})",
+ SampleCategoryEnum.sortedUnsorted.name(),
+ enumeration.PMFM_ID_SORTED_UNSORTED));
+ }
+ Integer qualitativeValueId = convertSampleCategoryValueIntoQualitativeId(source.getSampleCategoryValue());
+
+ parentBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", pmfmId, qualitativeValueId,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ // Parent Batch
+ target.setParentBatch(parentBatch);
+ }
+
+
+ if (parentBatch == null) {
+ throw new DataIntegrityViolationException(
+ "Could not retrieve parent batch, for a given speciesBatch : invalid batch tree structure. Please make sure CatchBatch has been saved before to create a SpeciesBatch.");
+ }
+
+ // Parent Batch
+ target.setParentBatch(parentBatch);
+ target.setRootBatch(catchBatch);
+ }
+
+ Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) {
+ if (value == null)
+ return null;
+ Integer qualitativeValueId = null;
+ if (value instanceof CaracteristicQualitativeValue) {
+ CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value;
+ qualitativeValueId = Integer.valueOf(cqValue.getId());
+ } else if (value instanceof String) {
+ qualitativeValueId = Integer.valueOf((String) value);
+ }
+ return qualitativeValueId;
+ }
+
+ protected void setSampleCategoryQualitative(SpeciesBatch target, Integer pmfmId, Float numericalvalue, String alphanumericalValue,
+ Integer qualitativeValueId) {
+ // skip if null or corresponding to the SORTING_TYPE PMFM (Expèce, Benthos, Plancton, etc.)
+ if (pmfmId == null || pmfmId.equals(enumeration.PMFM_ID_SORTING_TYPE)) {
+ return;
+ }
+
+ SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
+ Preconditions.checkNotNull(sampleCategory, "Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId);
+
+ target.setSampleCategoryType(sampleCategory);
+ if (numericalvalue != null) {
+ target.setSampleCategoryValue(numericalvalue);
+ return;
+ }
+ if (alphanumericalValue != null) {
+ target.setSampleCategoryValue(alphanumericalValue);
+ return;
+ }
+
+ Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId);
+ if (caracteristic == null || caracteristic.getCaracteristicType() != CaracteristicType.QUALITATIVE) {
+ return;
+ }
+ CaracteristicQualitativeValue value = null;
+ for (CaracteristicQualitativeValue qv : caracteristic.getQualitativeValue()) {
+ if (qualitativeValueId == Integer.parseInt(qv.getId())) {
+ value = qv;
+ break;
+ }
+ }
+ target.setSampleCategoryValue(value);
+ }
+
+ protected void beanToEntity(SpeciesBatchFrequency source, SortingBatch target, SortingBatch parentBatch, short rankOrder, boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getBatch());
+ Preconditions.checkNotNull(source.getBatch().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // If parent and root need to be set
+ if (target.getId() == null
+ || target.getRootBatch() == null
+ || (target.getParentBatch() != null && !target.getParentBatch().getId().equals(parentBatch.getId()))) {
+
+ target.setParentBatch(parentBatch);
+ target.setRootBatch(parentBatch.getRootBatch());
+ }
+
+ // RankOrder
+ target.setRankOrder(rankOrder);
+
+ // Weight or SampleCategoryWeight
+ if (copyIfNull && source.getWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getWeight() != null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sorting measurement
+ if (copyIfNull && (source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getLengthStepCaracteristic() != null && source.getLengthStep() != null) {
+ Integer pmfmId = Integer.valueOf(source.getLengthStepCaracteristic().getId());
+ SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, pmfmId,
+ source.getLengthStep());
+ notChangedSortingMeasurements.remove(sortingMeasurement);
+ }
+
+ // Individual count
+ if (copyIfNull && source.getNumber() == null) {
+ target.setIndividualCount(null);
+ } else if (source.getNumber() != null) {
+ target.setIndividualCount(source.getNumber());
+ }
+
+ // Species
+ target.setReferenceTaxon(null);
+
+ // QualityFlag
+ target.setQualityFlag(parentBatch.getQualityFlag());
+
+ // Comments
+ if (copyIfNull && source.getComment() == null) {
+ target.setComments(null);
+ } else if (source.getComment() != null) {
+ target.setComments(source.getComment());
+ }
+
+ // Exhaustive inventory (always true under a species batch)
+ target.setExhaustiveInventory(true);
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected UIWeight convertDatabase2UI(Float weight, Float samplingRatio, String samplingRatioText) {
+ UIWeight result = new UIWeight();
+
+ // Weight & sampleCategory Weight
+ if (samplingRatio == null) {
+ result.sampleCategoryWeight = weight;
+ } else if (weight != null) {
+ String startStr = weight.toString().replace(',', '.') + "/";
+ if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
+ String weightStr = samplingRatioText.substring(startStr.length());
+ if (weightStr != null && !weightStr.isEmpty()) {
+ result.sampleCategoryWeight = Float.parseFloat(weightStr);
+ result.weight = weight;
+ }
+ } else {
+ result.sampleCategoryWeight = weight;
+ }
+ }
+ return result;
+ }
+
+ static class UIWeight {
+ Float sampleCategoryWeight = null;
+
+ Float weight = null;
+ }
+
+ protected void beanToEntity(CatchBatch source,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch target,
+ boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // First initialization (when created)
+ Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId());
+ target.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId));
+
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRankOrder((short) 1);
+ target.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue());
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+
+ // Total Weight
+ if (copyIfNull && source.getCatchTotalWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (source.getCatchTotalWeight() != null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getCatchTotalWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ Map<Integer, SortingBatch> catchBatchChilds = getChildsMap(target, enumeration.PMFM_ID_SORTED_UNSORTED);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac
+ // -----------------------------------------------------------------------------
+ {
+ SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_VRAC_ID);
+ if (batch == null) {
+ batch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(batch);
+ }
+ beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
+ source.getCatchTotalSortedCarousselWeight(), source.getCatchTotalSortedTremisWeight(),
+ copyIfNull);
+ batch.setRankOrder((short) 1);
+
+ // Manage childs :
+ {
+ Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species
+ // -----------------------------------------------------------------------------
+ SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ if (speciesBatch == null) {
+ speciesBatch = SortingBatch.Factory.newInstance();
+ if (batch.getChildBatchs() == null) {
+ batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
+ } else {
+ batch.getChildBatchs().add(speciesBatch);
+ }
+ }
+ beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
+ source.getSpeciesTotalSampleSortedWeight(), source.getSpeciesTotalSortedWeight(),
+ copyIfNull);
+ speciesBatch.setRankOrder((short) 1);
+
+ {
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species / Alive not itemized
+ // -----------------------------------------------------------------------------
+ SortingBatch aliveNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
+ if (aliveNotItemizedBatch == null) {
+ aliveNotItemizedBatch = SortingBatch.Factory.newInstance();
+ if (speciesBatch.getChildBatchs() == null) {
+ speciesBatch.setChildBatchs(Lists.newArrayList((Batch) aliveNotItemizedBatch));
+ } else {
+ speciesBatch.getChildBatchs().add(aliveNotItemizedBatch);
+ }
+ }
+ beanToEntityReferenceTaxonBatch(target, speciesBatch, aliveNotItemizedBatch, recorderDepartmentId,
+ enumeration.REFERENCE_TAXON_ID_LIFE,
+ source.getSpeciesTotalLivingNotItemizedWeight(), null,
+ copyIfNull);
+ aliveNotItemizedBatch.setRankOrder((short) 1);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species / Inert (not alive)
+ // -----------------------------------------------------------------------------
+ SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
+ if (inertBatch == null) {
+ inertBatch = SortingBatch.Factory.newInstance();
+ speciesBatch.getChildBatchs().add(inertBatch);
+ }
+ beanToEntityReferenceTaxonBatch(target, speciesBatch, inertBatch, recorderDepartmentId,
+ enumeration.REFERENCE_TAXON_ID_INERT,
+ source.getSpeciesTotalInertWeight(), null,
+ copyIfNull);
+ inertBatch.setRankOrder((short) 2);
+ }
+ }
+ // TODO BL : benthos, plancton, macro déchet...
+ }
+
+ // -----------------------------------------------------------------------------
+ // Sorted Hors Vrac
+ // -----------------------------------------------------------------------------
+ {
+ SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_HORS_VRAC_ID);
+ if (batch == null) {
+ batch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(batch);
+ }
+ beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
+ source.getCatchTotalUnsortedWeight(), null,
+ copyIfNull);
+ batch.setRankOrder((short) 2);
+
+ // Manage childs :
+ {
+ Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
+
+ // Species :
+ SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ if (speciesBatch == null) {
+ speciesBatch = SortingBatch.Factory.newInstance();
+ if (batch.getChildBatchs() == null) {
+ batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
+ } else {
+ batch.getChildBatchs().add(speciesBatch);
+ }
+ }
+ beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
+ source.getSpeciesTotalUnsortedWeight(), null,
+ copyIfNull);
+ speciesBatch.setRankOrder((short) 1);
+ }
+
+ // TODO BL : benthos, plancton, macro déchet...
+ }
+
+ // -----------------------------------------------------------------------------
+ // Unsorted (=rejected)
+ // -----------------------------------------------------------------------------
+ // Unsorted :
+ SortingBatch unsortedBatch = catchBatchChilds.get(enumeration.QUALITATIVE_UNSORTED_ID);
+ if (unsortedBatch == null) {
+ unsortedBatch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(unsortedBatch);
+ }
+ beanToEntitySortingBatch(target, target, unsortedBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID,
+ source.getCatchTotalRejectedWeight(), null,
+ copyIfNull);
+ unsortedBatch.setRankOrder((short) 3);
+
+ }
+
+ protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) {
+ Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
+ if (parentBatch.getChildBatchs() == null) {
+ return batchByQualitativeValueId;
+ }
+ for (Batch childBatch : parentBatch.getChildBatchs()) {
+ SortingBatch childSortingBatch = (SortingBatch) childBatch;
+ SortingMeasurement sm = measurementHelper.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false);
+ if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) {
+ batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), childSortingBatch);
+ }
+ }
+ return batchByQualitativeValueId;
+ }
+
+ /**
+ * Retrieve child batchs if species is "Life" or "No life"
+ * (need to retrieve: speciesTotalLivingNotItemizedWeight and speciesTotalInertWeight)
+ *
+ * @param parentBatch
+ * @return
+ */
+ protected Map<Integer, SortingBatch> getChildAliveNotSortedOrInert(Batch parentBatch) {
+ Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
+ if (parentBatch.getChildBatchs() == null) {
+ return batchByQualitativeValueId;
+ }
+ for (Batch childBatch : parentBatch.getChildBatchs()) {
+ SortingBatch childSortingBatch = (SortingBatch) childBatch;
+ if (childSortingBatch.getReferenceTaxon() != null && childSortingBatch.getId().intValue() < 0) {
+ if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
+ batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
+ } else if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
+ batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
+ }
+ }
+ }
+ return batchByQualitativeValueId;
+ }
+
+ protected void beanToEntitySortingBatch(
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
+ fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
+ fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
+ Integer recorderDepartmentId,
+ Integer sortingPmfmId,
+ Integer sortingQualitativeValueId,
+ Float weight,
+ Float sampleWeight,
+ boolean copyIfNull) {
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // Some mandatory properties :
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRootBatch(rootBatch);
+ target.setParentBatch(parentBatch);
+ target.setExhaustiveInventory(true);
+
+ // No taxon or taxon group
+ target.setReferenceTaxon(null);
+ target.setTaxonGroup(null);
+
+ // Sorting measurement
+ if (copyIfNull && (sortingPmfmId == null || sortingQualitativeValueId == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (sortingPmfmId != null && sortingQualitativeValueId != null) {
+ SortingMeasurement sm = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId);
+ notChangedSortingMeasurements.remove(sm);
+ }
+
+ // Sampling Ratio
+ if (copyIfNull && (sampleWeight == null || weight == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (sampleWeight != null && weight != null) {
+ String samplingRatioText = weight + "/" + sampleWeight;
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(weight / sampleWeight);
+ }
+
+ // Weight
+ if (copyIfNull && (sampleWeight == null && weight == null)) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (sampleWeight != null || weight != null) {
+ Float batchReferenceWeight = weight;
+ if (batchReferenceWeight == null) {
+ batchReferenceWeight = sampleWeight;
+ }
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected void beanToEntityReferenceTaxonBatch(
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
+ fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
+ fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
+ Integer recorderDepartmentId,
+ Integer referenceTaxonId,
+ Float weight,
+ Float sampleWeight,
+ boolean copyIfNull) {
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // Some mandatory properties :
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRootBatch(rootBatch);
+ target.setParentBatch(parentBatch);
+ target.setExhaustiveInventory(true);
+
+ // Reference taxon
+ target.setReferenceTaxon(load(ReferenceTaxonImpl.class, referenceTaxonId));
+ target.setTaxonGroup(null);
+
+ // Sampling Ratio
+ if (copyIfNull && (sampleWeight == null || weight == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (sampleWeight != null && weight != null) {
+ String samplingRatioText = weight + "/" + sampleWeight;
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(weight / sampleWeight);
+ }
+
+ // Weight
+ if (copyIfNull && (sampleWeight == null && weight == null)) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (sampleWeight != null || weight != null) {
+ Float batchReferenceWeight = weight;
+ if (batchReferenceWeight == null) {
+ batchReferenceWeight = sampleWeight;
+ }
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected Integer getRecorderDepartmentId() {
+ // TODO BL : voir si on peut récupérer le departement (du 1er saisisseur ?)
+ return enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
+ }
+}
Deleted: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -1,437 +0,0 @@
-package fr.ifremer.tutti.persistence.service;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * 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%
- */
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import fr.ifremer.adagio.core.dao.data.batch.Batch;
-import fr.ifremer.adagio.core.dao.data.batch.CatchBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
-import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
-import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
-import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
-import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
-import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus;
-import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
-import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.FlushMode;
-import org.hibernate.type.IntegerType;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.DataRetrievalFailureException;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.Resource;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.0
- */
-@Service("catchBatchPersistenceService")
-public class CatchBatchPersistenceServiceImpl extends AbstractPersistenceService implements CatchBatchPersistenceService {
-
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(CatchBatchPersistenceServiceImpl.class);
-
- @Resource(name = "referentialPersistenceService")
- protected ReferentialPersistenceService referentialService;
-
- @Resource(name = "denormalizedBatchDao")
- protected DenormalizedBatchDao denormalizedBatchDao;
-
- @Resource(name = "sortingBatchDao")
- protected SortingBatchDao sortingBatchDao;
-
- @Resource(name = "catchBatchDao")
- protected CatchBatchDao catchBatchDao;
-
- @Resource(name = "measurementPersistenceHelper")
- protected MeasurementPersistenceHelper measurementHelper;
-
-
- @Override
- public CatchBatch getCatchBatchFromFishingOperation(String id) {
- Preconditions.checkNotNull(id);
-
- Iterator<Object[]> list = queryList("catchBatch",
- "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(id),
- "pmfmIdSorted", IntegerType.INSTANCE, enumeration.PMFM_ID_SORTED_UNSORTED,
- "pmfmIdSortingType", IntegerType.INSTANCE, enumeration.PMFM_ID_SORTING_TYPE);
-
- int rowCount = 0;
- CatchBatch result = new CatchBatch();
- Integer previousSortedBatchId = null;
- while (list.hasNext()) {
- Object[] source = list.next();
- rowCount++;
-
- if (rowCount == 1) {
- // Id
- result.setId(source[0].toString());
-
- // Total weight
- Float totalWeight = (Float) source[1];
- result.setCatchTotalWeight(totalWeight);
- }
-
- Integer sortedBatchId = (Integer) source[2];
- Integer sortedQualitativeValueId = (Integer) source[5];
- if (sortedBatchId != null && !sortedBatchId.equals(previousSortedBatchId)) {
- // TODO BL : retrieve QV
- String samplingRatioText = (String) source[3];
- Float weight = (Float) source[4];
- if (weight != null && enumeration.QUALITATIVE_VRAC_ID.equals(sortedQualitativeValueId)) {
- result.setCatchTotalSortedCarousselWeight(weight);
- result.setCatchTotalSortedTremisWeight(getTotalWeight(weight, samplingRatioText));
- } else if (weight != null && enumeration.QUALITATIVE_HORS_VRAC_ID.equals(sortedQualitativeValueId)) {
- result.setCatchTotalUnsortedWeight(weight);
- if (samplingRatioText != null && !samplingRatioText.isEmpty()) {
- // TODO BL : throw error because baths are not compatible with tutti ??
- }
- } else if (weight != null && enumeration.QUALITATIVE_UNSORTED_ID.equals(sortedQualitativeValueId)) {
- result.setCatchTotalRejectedWeight(weight);
- if (samplingRatioText != null && !samplingRatioText.isEmpty()) {
- // TODO BL : throw error because baths are not compatible with tutti ??
- }
- }
- }
-
- Integer sortingTypeBatchId = (Integer) source[6];
- {
- String samplingRatioText = (String) source[7];
- Float weight = (Float) source[8];
- Integer qualitativeValueId = (Integer) source[9];
- if (weight != null) {
- if (enumeration.QUALITATIVE_VRAC_ID.equals(sortedQualitativeValueId)
- && enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES.equals(qualitativeValueId)) {
- result.setSpeciesTotalSampleSortedWeight(weight);
- result.setSpeciesTotalSortedWeight(getTotalWeight(weight, samplingRatioText));
- } else if (enumeration.QUALITATIVE_HORS_VRAC_ID.equals(sortedQualitativeValueId)
- && enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES.equals(qualitativeValueId)) {
- result.setSpeciesTotalUnsortedWeight(weight);
- // TODO error si samplingRatio not null
- }
- // TOBO BL : add benthos, plancton, etc.
- }
- }
-
-
- previousSortedBatchId = sortedBatchId;
- }
-
- return result;
- }
-
- @Override
- public CatchBatch createCatchBatch(CatchBatch bean) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkArgument(bean.getId() == null);
- Preconditions.checkNotNull(bean.getFishingOperation());
- Preconditions.checkNotNull(bean.getFishingOperation().getId());
-
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = fr.ifremer.adagio.core.dao.data.batch.CatchBatch.Factory.newInstance();
- beanToEntity(bean, catchBatch, true);
- catchBatch = catchBatchDao.create(catchBatch);
- bean.setId(String.valueOf(catchBatch.getId()));
-
- // Link to fishing operation
- getCurrentSession().flush();
- Integer fishingOperationId = Integer.valueOf(bean.getFishingOperation().getId());
- int rowUpdated = queryUpdate("updateFishingOperationCatchBatch",
- "fishingOperationId", IntegerType.INSTANCE, fishingOperationId,
- "catchBatchId", IntegerType.INSTANCE, catchBatch.getId());
- if (rowUpdated == 0) {
- throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found.");
- }
-
- return bean;
- }
-
- @Override
- public CatchBatch saveCatchBatch(CatchBatch bean) {
-
- Preconditions.checkNotNull(bean);
- Preconditions.checkNotNull(bean.getId());
-
- getCurrentSession().enableFetchProfile("batch-with-childs");
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(Integer.valueOf(bean.getId()));
- if (catchBatch == null) {
- throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId());
- }
-
- beanToEntity(bean, catchBatch, true);
- catchBatchDao.update(catchBatch);
- getCurrentSession().flush();
- return bean;
- }
-
- // ------------------------------------------------------------------------//
- // -- Internal methods --//
- // ------------------------------------------------------------------------//
- protected void beanToEntity(CatchBatch source,
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch target,
- boolean copyIfNull) {
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve recorder department
- // TODO BLA : prendre le service du 1er saisisseur sur l'OP ?
- Integer recorderDepartmentId = enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
-
- // First initialization (when created)
- Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId());
- target.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId));
-
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRankOrder((short) 1);
- target.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue());
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
-
- // Total Weight
- if (copyIfNull && source.getCatchTotalWeight() == null) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (source.getCatchTotalWeight() != null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getCatchTotalWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- Map<Integer, SortingBatch> catchBatchChilds = getChildsMap(target, enumeration.PMFM_ID_SORTED_UNSORTED);
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac
- // -----------------------------------------------------------------------------
- {
- SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_VRAC_ID);
- if (batch == null) {
- batch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(batch);
- }
- beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
- source.getCatchTotalSortedTremisWeight(), source.getCatchTotalSortedCarousselWeight(),
- copyIfNull);
- batch.setRankOrder((short) 1);
-
- // Manage childs :
- {
- Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
-
- // Species :
- SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- if (speciesBatch == null) {
- speciesBatch = SortingBatch.Factory.newInstance();
- if (batch.getChildBatchs() == null) {
- batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
- } else {
- batch.getChildBatchs().add(speciesBatch);
- }
- }
- beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
- source.getSpeciesTotalSortedWeight(), source.getSpeciesTotalSampleSortedWeight(),
- copyIfNull);
- speciesBatch.setRankOrder((short) 1);
- }
- // TODO BL : benthos, plancton, macro déchet...
- }
-
- // -----------------------------------------------------------------------------
- // Sorted Hors Vrac
- // -----------------------------------------------------------------------------
- {
- SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_HORS_VRAC_ID);
- if (batch == null) {
- batch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(batch);
- }
- beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
- source.getCatchTotalUnsortedWeight(), null,
- copyIfNull);
- batch.setRankOrder((short) 2);
-
- // Manage childs :
- {
- Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
-
- // Species :
- SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- if (speciesBatch == null) {
- speciesBatch = SortingBatch.Factory.newInstance();
- if (batch.getChildBatchs() == null) {
- batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
- } else {
- batch.getChildBatchs().add(speciesBatch);
- }
- }
- beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
- source.getSpeciesTotalUnsortedWeight(), null,
- copyIfNull);
- speciesBatch.setRankOrder((short) 1);
- }
-
- // TODO BL : benthos, plancton, macro déchet...
- }
-
- // -----------------------------------------------------------------------------
- // Unsorted (=rejected)
- // -----------------------------------------------------------------------------
- // Unsorted :
- SortingBatch unsortedBatch = catchBatchChilds.get(enumeration.QUALITATIVE_UNSORTED_ID);
- if (unsortedBatch == null) {
- unsortedBatch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(unsortedBatch);
- }
- beanToEntitySortingBatch(target, target, unsortedBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID,
- source.getCatchTotalRejectedWeight(), null,
- copyIfNull);
- unsortedBatch.setRankOrder((short) 3);
-
-
- }
-
- protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) {
- Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
- if (parentBatch.getChildBatchs() == null) {
- return batchByQualitativeValueId;
- }
- for (Batch childBatch : parentBatch.getChildBatchs()) {
- SortingMeasurement sm = measurementHelper.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false);
- if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) {
- batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), (SortingBatch) childBatch);
- }
- }
- return batchByQualitativeValueId;
- }
-
- protected void beanToEntitySortingBatch(
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
- fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
- fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
- Integer recorderDepartmentId,
- Integer sortingPmfmId,
- Integer sortingQualitativeValueId,
- Float weight,
- Float sampleWeight,
- boolean copyIfNull) {
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // Some mandatory properties :
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRootBatch(rootBatch);
- target.setParentBatch(parentBatch);
-
- // Sorting measurement
- if (copyIfNull && (sortingPmfmId == null || sortingQualitativeValueId == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (sortingPmfmId != null && sortingQualitativeValueId != null) {
- SortingMeasurement sm = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId);
- notChangedSortingMeasurements.remove(sm);
- }
-
- // Sampling Ratio
- if (copyIfNull && (sampleWeight == null || weight == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (sampleWeight != null && weight != null) {
- String samplingRatioText = sampleWeight + "/" + weight;
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(sampleWeight / weight);
- }
-
- // Weight
- if (copyIfNull && (sampleWeight == null && weight == null)) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (sampleWeight != null || weight != null) {
- Float batchReferenceWeight = sampleWeight;
- if (batchReferenceWeight == null) {
- batchReferenceWeight = weight;
- }
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- protected Float getTotalWeight(Float weight, String samplingRatioText) {
- if (weight == null) {
- return null;
- }
- String startStr = weight.toString().replace(',', '.') + "/";
- if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
- String weightStr = samplingRatioText.substring(startStr.length());
- if (weightStr != null && !weightStr.isEmpty()) {
- return Float.parseFloat(weightStr);
- }
- }
- // TODO BL : attention au saise "1/2" qui ne seront pas pris (mais "1.0/2.0" oui)
- return null;
- }
-
-}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -188,7 +188,9 @@
Caracteristic getCaracteristic(Integer pmfmId);
boolean isSortedQualitativeValue(CaracteristicQualitativeValue value);
-
+
+ List<Integer> getSampleCategoryIds();
+
/**
* Import given temporary species.
*
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -815,6 +815,20 @@
}
/**
+ * Return list of protected pmfm for sample category
+ * (i.e. to check the validity of a existing batch tree)
+ *
+ * @return
+ */
+ public List<Integer> getSampleCategoryIds() {
+ return Lists.newArrayList(enumeration.PMFM_ID_SORTED_UNSORTED
+ , enumeration.PMFM_ID_SIZE_CATEGORY
+ , enumeration.PMFM_ID_MATURITY
+ , enumeration.PMFM_ID_SEX
+ , enumeration.PMFM_ID_AGE);
+ }
+
+ /**
* Return true if the pmfm should NOT be used for caracteristics lists
* (i.e. because used somewhere when storing some properties into the database)
*
Deleted: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -1,812 +0,0 @@
-package fr.ifremer.tutti.persistence.service;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * 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%
- */
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import fr.ifremer.adagio.core.dao.data.batch.CatchBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.CatchBatchImpl;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatchImpl;
-import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
-import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
-import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
-import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
-import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
-import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
-import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
-import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
-import fr.ifremer.tutti.persistence.entities.referential.Species;
-import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.FlushMode;
-import org.hibernate.type.IntegerType;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.Resource;
-import java.io.Serializable;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.3
- */
-@Service("speciesBatchPersistenceService")
-public class SpeciesBatchPersistenceServiceImpl extends
- AbstractPersistenceService implements SpeciesBatchPersistenceService {
-
- /** Logger. */
- private static final Log log = LogFactory
- .getLog(SpeciesBatchPersistenceServiceImpl.class);
-
- @Resource(name = "referentialPersistenceService")
- protected ReferentialPersistenceService referentialService;
-
- @Resource(name = "denormalizedBatchDao")
- protected DenormalizedBatchDao denormalizedBatchDao;
-
- @Resource(name = "sortingBatchDao")
- protected SortingBatchDao sortingBatchDao;
-
- @Resource(name = "catchBatchDao")
- protected CatchBatchDao catchBatchDao;
-
- @Resource(name = "measurementPersistenceHelper")
- protected MeasurementPersistenceHelper measurementHelper;
-
- @Override
- public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) {
- Iterator<Object[]> list = queryList("allSpeciesBatch",
- "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(fishingOperationId));
-
- List<SpeciesBatch> result = new ArrayList<SpeciesBatch>();
- List<SpeciesBatch> rootBatchs = new ArrayList<SpeciesBatch>();
-
- Map<String, SpeciesBatch> batchMapById = new HashMap<String, SpeciesBatch>();
- //TODO BLA : uncomment if a property speciesBatch.speciesBatchFrequency exists
- //Map<String, List<SpeciesBatchFrequency>> batchFrequenciesMapByParentId = new HashMap<String, List<SpeciesBatchFrequency>>();
- Map<String, String> parentBatchMapById = new HashMap<String, String>();
- while (list.hasNext()) {
- Object[] source = list.next();
-
- Integer parentbatchId = (Integer) source[11];
-
- // If row is not a species batch, load as batch frequency
- if (couldBeASpeciesBatchFrequency(source)) {
- //TODO BLA : uncomment if a property speciesBatch.speciesBatchFrequency exists
- //loadSpeciesBatchFrequency(source, batchFrequenciesMapByParentId);
- } else {
- // In all case, load row as species batch
- SpeciesBatch speciesBatch = loadSpeciesBatch(source);
-
- // Add result into a maps
- batchMapById.put(speciesBatch.getId(), speciesBatch);
- if (parentbatchId != null) {
- parentBatchMapById.put(speciesBatch.getId(), parentbatchId.toString());
- }
- }
- }
-
- // Retrieve the parent links for all batchs
- for (SpeciesBatch speciesBatch : batchMapById.values()) {
- // If retrieve the parent from the parent map
- String parentbatchId = parentBatchMapById.get(speciesBatch.getId());
- if (parentbatchId != null) {
- SpeciesBatch parentSpeciesBatch = batchMapById.get(parentbatchId);
-
- // If found, link the batch with its parent :
- if (parentSpeciesBatch != null) {
- speciesBatch.setParentBatch(parentSpeciesBatch);
- if (parentSpeciesBatch.getChildBatchs() == null) {
- parentSpeciesBatch.setChildBatchs(Lists.newArrayList(speciesBatch));
- } else {
- parentSpeciesBatch.addChildBatchs(speciesBatch);
- }
- }
-
- // If no parent found, the batch should be a direct child of the catch batch
- else {
- rootBatchs.add(speciesBatch);
- }
-
- //TODO BLA : uncomment if a property speciesBatch.speciesBatchFrequency exists
- //List<SpeciesBatchFrequency> batchFrequencies = batchFrequenciesMapByParentId.get(speciesBatch.getId());
- //if (batchFrequencies != null) {
- // speciesBatch.setSpeciesBatchFrequency(batchFrequencies);
- //}
- }
- }
-
- // Apply inheritance, starting with the catch batch children
- applyInheritedProperties(rootBatchs, null, null, result);
-
- return result;
- }
-
- @Override
- public SpeciesBatch createSpeciesBatch(SpeciesBatch bean,
- String parentBatchId) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkArgument(bean.getId() == null);
- Preconditions.checkNotNull(bean.getSpecies());
- Preconditions.checkNotNull(bean.getSpecies().getId());
- Preconditions.checkNotNull(bean.getFishingOperation());
- Preconditions.checkNotNull(bean.getFishingOperation().getId());
- // TODO BLA uncomment this after v1.0 :
- //Preconditions.checkNotNull(bean.getCatchBatch());
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- SortingBatch batch = SortingBatch.Factory.newInstance();
- beanToEntity(bean, batch, parentBatchId, true);
- batch = sortingBatchDao.create(batch);
-
- bean.setId(String.valueOf(batch.getId()));
-
- getCurrentSession().flush();
-
- return bean;
- }
-
- @Override
- public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkNotNull(bean.getId());
-
- // TODO BL : pourquoi un clear() ? => pas nécessaire.
- //getCurrentSession().clear();
-
- getCurrentSession().enableFetchProfile("batch-with-measurements");
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
- SortingBatch batch = sortingBatchDao.load(Integer.valueOf(bean.getId()));
- String parentBatchId = null;
- if (bean.getParentBatch() != null) {
- parentBatchId = bean.getParentBatch().getId();
- }
- beanToEntity(bean, batch, parentBatchId, true);
- sortingBatchDao.update(batch);
- getCurrentSession().flush();
- return bean;
- }
-
- @Override
- public void deleteSpeciesBatch(String id) {
- Preconditions.checkNotNull(id);
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- List<SortingBatch> allChildrenBatchs = Lists.newArrayList();
- removeAllChildrenBatchs(Integer.valueOf(id), allChildrenBatchs);
-
- getCurrentSession().flush();
- }
-
- @Override
- public void deleteSpeciesSubBatch(String id) {
- deleteSpeciesBatch(id);
- }
-
- @Override
- public void changeSpeciesBatchSpecies(String batchId, Species species) {
- Preconditions.checkNotNull(batchId);
- Preconditions.checkNotNull(species);
- Preconditions.checkNotNull(species.getReferenceTaxonId());
-
- if (log.isDebugEnabled()) {
- log.debug("Changing species for batch id="+batchId);
- }
-
- int rowUpdated = queryUpdate("updateBatchSpecies",
- "batchId", IntegerType.INSTANCE, Integer.valueOf(batchId),
- "referenceTaxonId", IntegerType.INSTANCE, species.getReferenceTaxonId());
- }
-
- @Override
- public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
- String speciesBatchId) {
- Iterator<Object[]> list = queryList("allSpeciesBatchFrequency",
- "parentBatchId", IntegerType.INSTANCE, Integer.valueOf(speciesBatchId));
-
- List<SpeciesBatchFrequency> results = Lists.newArrayList();
-
- while (list.hasNext()) {
- Object[] source = list.next();
- SpeciesBatchFrequency target = new SpeciesBatchFrequency();
-
- int colIndex = 0;
- target.setId(source[colIndex++].toString());
-
- target.setNumber((Integer) source[colIndex++]);
- target.setWeight((Float) source[colIndex++]);
- target.setComment((String) source[colIndex++]);
-
- // Length step category
- Integer lengthPmfmId = (Integer) source[colIndex++];
- Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(lengthPmfmId);
- target.setLengthStepCaracteristic(lengthStepCaracteristic);
-
- // Length
- target.setLengthStep((Float) source[colIndex++]);
- results.add(target);
- }
- return results;
- }
-
-
- @Override
- public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(
- String speciesBatchId, List<SpeciesBatchFrequency> frequencies) {
- Preconditions.checkNotNull(speciesBatchId);
- Preconditions.checkNotNull(frequencies);
-
- if (frequencies.size() == 0) {
- return frequencies;
- }
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
- getCurrentSession().enableFetchProfile("batch-with-measurements");
-
- // Retirve parent
- SortingBatch parentBatch = sortingBatchDao.load(Integer.valueOf(speciesBatchId));
-
- short rankOrder = 0;
- String pmfmId = null;
- Map<SortingBatch, SpeciesBatchFrequency> batchsToCreate = Maps.newHashMap();
- List<SortingBatch> batchsToUpdate = Lists.newArrayList();
- for (SpeciesBatchFrequency source : frequencies) {
- rankOrder++;
-
- // Check that all frequencies have the same length PMFM
- if (pmfmId == null) {
- source.getLengthStepCaracteristic().getId();
- } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) {
- throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic");
- }
-
- // Not existing batch
- SortingBatch target = null;
- if (source.getId() == null) {
- target = SortingBatch.Factory.newInstance();
-
- // Fill the sorting batch from the source
- beanToEntity(source, target, parentBatch, rankOrder, true);
-
- // Create the targeted batch, then update the source id
- sortingBatchDao.create(target);
- source.setId(target.getId().toString());
- }
-
- // Existing batch
- else {
- target = sortingBatchDao.load(Integer.valueOf(source.getId()));
-
- // Fill the sorting batch from the source
- beanToEntity(source, target, parentBatch, rankOrder, true);
-
- // Add the batch into a list (will be update later, using this list)
- batchsToUpdate.add(target);
- }
- }
-
- // If some batchs need to be update, do it
- if (batchsToUpdate.size() > 0) {
- sortingBatchDao.update(batchsToUpdate);
- }
-
- getCurrentSession().flush();
-
- return frequencies;
- }
-
- // ------------------------------------------------------------------------//
- // -- Internal methods --//
- // ------------------------------------------------------------------------//
- protected void beanToEntity(SpeciesBatch source, SortingBatch target, String parentBatchId, boolean copyIfNull) {
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve recorder department
- // TODO BLA : prendre le service du 1er saisisseur ?
- Integer recorderDepartmentId = enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // If parent and root need to be set
- if (target.getId() == null
- || target.getRootBatch() == null
- || (target.getParentBatch() != null && !target.getParentBatch().getId().toString().equals(parentBatchId))) {
- setBatchParents(source, target, parentBatchId, notChangedSortingMeasurements);
- }
-
- // RankOrder
- if (target.getRankOrder() == null) {
- short rankOrder = (short) 1;
- if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) {
- // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?)
- rankOrder = (short) source.getParentBatch().getChildBatchs().size();
- }
- target.setRankOrder(rankOrder);
- }
-
- // Weight or SampleCategoryWeight
- if (copyIfNull && source.getWeight() == null && source.getSampleCategoryWeight() == null) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getSampleCategoryWeight() != null && source.getWeight() == null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sampling Ratio
- if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) {
- String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight();
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight());
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sorting measurement
- if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) {
- Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
- // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch)
- if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
- SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, source.getSampleCategoryType(), source.getSampleCategoryValue());
- notChangedSortingMeasurements.remove(sortingMeasurement);
- }
- }
-
- // Individual count
- if (copyIfNull && source.getNumber() == null) {
- target.setIndividualCount(null);
- } else if (source.getNumber() != null) {
- target.setIndividualCount(source.getNumber());
- }
-
- // Species
- if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) {
- target.setReferenceTaxon(null);
- } else if (source.getSpecies() != null && parentBatchId == null) {
- ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId());
- target.setReferenceTaxon(referenceTaxon);
- }
-
- // QualityFlag
- if (source.isSpeciesToConfirm()) {
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL));
- } else {
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- }
-
- // Comments
- if (copyIfNull && source.getComment() == null) {
- target.setComments(null);
- } else if (source.getComment() != null) {
- target.setComments(source.getComment());
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- public void setBatchParents(SpeciesBatch source, SortingBatch target, String parentBatchIdStr,
- Set<SortingMeasurement> notChangedSortingMeasurements) {
-
- Preconditions.checkNotNull(target);
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve parent and root batch
- if (parentBatchIdStr == null) {
- // Retrieve category type
- Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
- if (pmfmId == null || !pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
- throw new DataIntegrityViolationException(MessageFormat.format("A species batch with no parent should have a sampleCategoryType {0} (PMFM.ID={1})",
- SampleCategoryEnum.sortedUnsorted.name(), enumeration.PMFM_ID_SORTED_UNSORTED));
- }
- Integer qualitativeValueId = convertSampleCategoryValueIntoQualitativeId(source.getSampleCategoryValue());
-
- Object[] cols = queryUnique("parentBatch",
- "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(source.getFishingOperation().getId()),
- "pmfmIdSorted", IntegerType.INSTANCE, enumeration.PMFM_ID_SORTED_UNSORTED,
- "qualitativeIdSorted", IntegerType.INSTANCE, qualitativeValueId,
- "pmfmIdSortingType", IntegerType.INSTANCE, enumeration.PMFM_ID_SORTING_TYPE,
- "qualitativeIdSortingType", IntegerType.INSTANCE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
-
- if (cols == null) {
- throw new DataIntegrityViolationException("Catch batchs not presents, or invalid batch tree structure. Please make sure CatchBatch has been saved before to create a SpeciesBatch.");
- }
- // Parent Batch
- Integer parentBatchId = (Integer) cols[0];
- SortingBatch parentBatch = load(SortingBatchImpl.class, parentBatchId);
- target.setParentBatch(parentBatch);
-
- // Root Batch
- Integer rootBatchId = (Integer) cols[1];
- target.setRootBatch(load(CatchBatchImpl.class, rootBatchId));
- }
-
- // Load existing parent and root
- else {
- SortingBatch parentBatch = load(SortingBatchImpl.class, Integer.valueOf(parentBatchIdStr));
- target.setParentBatch(parentBatch);
- target.setRootBatch(parentBatch.getRootBatch());
- }
- }
-
- protected SpeciesBatch loadSpeciesBatch(Object[] source) {
- int colIndex = 0;
-
- SpeciesBatch result = new SpeciesBatch();
- result.setId(source[colIndex++].toString());
-
- // Individual count
- result.setNumber((Integer) source[colIndex++]);
-
- // Convert database weight (and sampling ratio) into UI weight and sampleCategoryWeight
- Float sourceWeight = (Float) source[colIndex++];
- Float sourceSamplingRatio = (Float) source[colIndex++];
- String sourceSamplingRatioText = (String) source[colIndex++];
- UIWeight uiWeight = convertDatabase2UI(sourceWeight, sourceSamplingRatio, sourceSamplingRatioText);
- result.setWeight(uiWeight.weight);
- result.setSampleCategoryWeight(uiWeight.sampleCategoryWeight);
-
- // Comments
- result.setComment((String) source[colIndex++]);
-
- // Sample category type
- Integer pmfmId = (Integer) source[colIndex++];
-
- // Sample category value
- Integer qvValue = (Integer) source[colIndex++];
- Float numValue = (Float) source[colIndex++];
- String alphaValue = (String) source[colIndex++];
- if (pmfmId != null) {
- setSampleCategoryQualitative(result, pmfmId, numValue, alphaValue, qvValue);
- }
-
- // Species
- Integer referenceTaxonId = (Integer) source[colIndex++];
- if (referenceTaxonId != null) {
- // TODO : add cache on getSpeciesByReferenceTaxonId
- Species species = referentialService.getSpeciesByReferenceTaxonId(referenceTaxonId);
- result.setSpecies(species);
- }
-
- return result;
- }
-
- protected void applyInheritedProperties(List<SpeciesBatch> speciesBatchs, CaracteristicQualitativeValue inheritedSortedUnsortedValue, Species inheritedSpecies, List<SpeciesBatch> results) {
- if (speciesBatchs == null || speciesBatchs.size() == 0) {
- return;
- }
- for (SpeciesBatch speciesBatch : speciesBatchs) {
- // If batch store a species (in the database)
- if (speciesBatch.getSpecies() != null) {
- // Remove the link to the parent (not need in UI)
- speciesBatch.setParentBatch(null);
- // Store into result list only if species has been set (=species root batch)
- results.add(speciesBatch);
- }
-
- // Apply sampleCategoryValue inheritance, if need
- if (inheritedSortedUnsortedValue != null && speciesBatch.getSampleCategoryType() == null) {
- speciesBatch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
- speciesBatch.setSampleCategoryValue(inheritedSortedUnsortedValue);
- }
-
- // Apply species inheritance, if need
- if (speciesBatch.getSpecies() == null && inheritedSpecies != null) {
- speciesBatch.setSpecies(inheritedSpecies);
- }
-
- // Compute the inheritance sorted/unsorted value for children
- if (speciesBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted) {
- inheritedSortedUnsortedValue = (CaracteristicQualitativeValue) speciesBatch.getSampleCategoryValue();
- } else {
- inheritedSortedUnsortedValue = null;
- }
-
- // Recursive call : propagate species and sorted/unsorted value
- applyInheritedProperties(speciesBatch.getChildBatchs(),
- inheritedSortedUnsortedValue,
- speciesBatch.getSpecies(),
- results);
- }
- }
-
- Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) {
- if (value == null) return null;
- Integer qualitativeValueId = null;
- if (value instanceof CaracteristicQualitativeValue) {
- CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value;
- qualitativeValueId = Integer.valueOf(cqValue.getId());
- } else if (value instanceof String) {
- qualitativeValueId = Integer.valueOf((String) value);
- }
- return qualitativeValueId;
- }
-
- protected void setSampleCategoryQualitative(SpeciesBatch target, Integer pmfmId, Float numericalvalue, String alphanumericalValue, Integer qualitativeValueId) {
- // skip if null or corresponding to the SORTING_TYPE PMFM (Expèce, Benthos, Plancton, etc.)
- if (pmfmId == null || pmfmId.equals(enumeration.PMFM_ID_SORTING_TYPE)) {
- return;
- }
-
- SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
- Preconditions.checkNotNull(sampleCategory, "Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId);
-
- target.setSampleCategoryType(sampleCategory);
- if (numericalvalue != null) {
- target.setSampleCategoryValue(numericalvalue);
- return;
- }
- if (alphanumericalValue != null) {
- target.setSampleCategoryValue(alphanumericalValue);
- return;
- }
-
- Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId);
- if (caracteristic == null || caracteristic.getCaracteristicType() != CaracteristicType.QUALITATIVE) {
- return;
- }
- CaracteristicQualitativeValue value = null;
- for (CaracteristicQualitativeValue qv : caracteristic.getQualitativeValue()) {
- if (qualitativeValueId == Integer.parseInt(qv.getId())) {
- value = qv;
- break;
- }
- }
- target.setSampleCategoryValue(value);
- }
-
- protected void removeAllChildrenBatchs(Integer batchId, List<SortingBatch> result) {
- Iterator<Integer> list = queryListTyped("speciesBatchChildren",
- "batchId", IntegerType.INSTANCE, batchId);
-
- // First, add childrens
- while (list.hasNext()) {
-
- removeAllChildrenBatchs(list.next(), result);
- }
-
- // Then add the given batch (after children, because of order need in "delete")
- SortingBatch batch = sortingBatchDao.load(batchId);
- //SortingBatch batch = (SortingBatch)getCurrentSession().get(SortingBatchImpl.class, batchId);
- batch.getSortingMeasurements().clear();
- batch.getQuantificationMeasurements().clear();
- sortingBatchDao.remove(batch);
- }
-
- protected void beanToEntity(SpeciesBatchFrequency source, SortingBatch target, SortingBatch parentBatch, short rankOrder, boolean copyIfNull) {
- Preconditions.checkNotNull(source.getBatch());
- Preconditions.checkNotNull(source.getBatch().getId());
-
- // Retrieve recorder department
- // TODO BLA : prendre le service du 1er saisisseur ?
- Integer recorderDepartmentId = enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // If parent and root need to be set
- if (target.getId() == null
- || target.getRootBatch() == null
- || (target.getParentBatch() != null && !target.getParentBatch().getId().equals(parentBatch.getId()))) {
-
- target.setParentBatch(parentBatch);
- target.setRootBatch(parentBatch.getRootBatch());
- }
-
- // RankOrder
- target.setRankOrder(rankOrder);
-
- // Weight or SampleCategoryWeight
- if (copyIfNull && source.getWeight() == null) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getWeight() != null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sorting measurement
- if (copyIfNull && (source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getLengthStepCaracteristic() != null && source.getLengthStep() != null) {
- Integer pmfmId = Integer.valueOf(source.getLengthStepCaracteristic().getId());
- SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, pmfmId, source.getLengthStep());
- notChangedSortingMeasurements.remove(sortingMeasurement);
- }
-
- // Individual count
- if (copyIfNull && source.getNumber() == null) {
- target.setIndividualCount(null);
- } else if (source.getNumber() != null) {
- target.setIndividualCount(source.getNumber());
- }
-
- // Species
- target.setReferenceTaxon(null);
-
- // QualityFlag
- target.setQualityFlag(parentBatch.getQualityFlag());
-
- // Comments
- if (copyIfNull && source.getComment() == null) {
- target.setComments(null);
- } else if (source.getComment() != null) {
- target.setComments(source.getComment());
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- private SpeciesBatchFrequency loadSpeciesBatchFrequency(Object[] source, Map<String, List<SpeciesBatchFrequency>> batchFrequenciesMapByParentId) {
- SpeciesBatchFrequency target = new SpeciesBatchFrequency();
-
- int colIndex = 0;
- target.setId(source[colIndex++].toString());
-
- // Individual count
- target.setNumber((Integer) source[colIndex++]);
-
- // Covert database weight (and sampling ratio) into UI weight
- Float sourceWeight = (Float) source[colIndex++];
- Float sourceSamplingRatio = (Float) source[colIndex++];
- String sourceSamplingRatioText = (String) source[colIndex++];
- UIWeight uiWeight = convertDatabase2UI(sourceWeight, sourceSamplingRatio, sourceSamplingRatioText);
- target.setWeight(uiWeight.weight);
-
- target.setComment((String) source[colIndex++]);
-
- // Length step category
- Integer lengthPmfmId = (Integer) source[colIndex++];
- Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(lengthPmfmId);
- target.setLengthStepCaracteristic(lengthStepCaracteristic);
-
- // Qualitative value (should be null)
- Preconditions.checkState(source[colIndex++] == null, "Invalid batch tree format : batch frequency could not have a qualitative value.");
-
- // Length (skip qvValue and alphaValue column)
- target.setLengthStep((Float) source[colIndex++]);
-
- // Alphanumerical value (should be null)
- Preconditions.checkState(source[colIndex++] == null, "Invalid batch tree format : batch frequency could not have a alphanumerical value.");
-
- // Taxon (should be null)
- Preconditions.checkState(source[colIndex++] == null, "Invalid batch tree format : taxon frequency could not have species.");
-
- Integer parentBatchId = (Integer) source[colIndex++];
-
- // Add target into the result map
- List<SpeciesBatchFrequency> parentBatchFrequencies = batchFrequenciesMapByParentId.get(parentBatchId.toString());
- if (parentBatchFrequencies == null) {
- parentBatchFrequencies = Lists.newArrayList();
- batchFrequenciesMapByParentId.put(parentBatchId.toString(), parentBatchFrequencies);
- }
- parentBatchFrequencies.add(target);
-
- return target;
- }
-
- protected boolean couldBeASpeciesBatchFrequency(Object[] source) {
- Integer pmfmId = (Integer) source[6];
- Integer referenceTaxonId = (Integer) source[10];
- Float numericalValue = (Float) source[8];
- Integer parentbatchId = (Integer) source[11];
- SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
-
- // Batch frequency is a batch with :
- // - a numerical value
- // - a parent
- // - no species
- // - no corresponding sample category
- return numericalValue != null && parentbatchId != null && referenceTaxonId == null && sampleCategory == null;
- }
-
- protected UIWeight convertDatabase2UI(Float weight, Float samplingRatio, String samplingRatioText) {
- UIWeight result = new UIWeight();
-
- // Weight & sampleCategory Weight
- if (samplingRatio == null) {
- result.sampleCategoryWeight = weight;
- } else if (weight != null) {
- String startStr = weight.toString().replace(',', '.') + "/";
- if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
- String weightStr = samplingRatioText.substring(startStr.length());
- if (weightStr != null && !weightStr.isEmpty()) {
- result.sampleCategoryWeight = Float.parseFloat(weightStr);
- result.weight = weight;
- }
- }
- else {
- result.sampleCategoryWeight = weight;
- }
- }
- return result;
- }
-
- static class UIWeight {
- Float sampleCategoryWeight = null;
-
- Float weight = null;
- }
-}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -188,6 +188,12 @@
@Value("${TaxonGroupTypeCode.COMMERCIAL_SPECIES}")
public final String TAXON_GROUP_TYPE_ID_COMMERCIAL_SPECIES = null;
+ @Value("${ReferenceTaxonId.LIFE}")
+ public final Integer REFERENCE_TAXON_ID_LIFE = null;
+
+ @Value("${ReferenceTaxonId.INERT}")
+ public final Integer REFERENCE_TAXON_ID_INERT = null;
+
public void init() {
Field[] declaredFields = getClass().getDeclaredFields();
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -80,13 +80,18 @@
FishingOperationPersistenceService.class);
}
+ public static BatchPersistenceService getBatchPersistenceService() {
+ return getPersistenceService("batchPersistenceService",
+ BatchPersistenceService.class);
+ }
+
public static CatchBatchPersistenceService getCatchBatchPersistenceService() {
- return getPersistenceService("catchBatchPersistenceService",
- CatchBatchPersistenceService.class);
+ return getPersistenceService("batchPersistenceService",
+ CatchBatchPersistenceService.class);
}
public static SpeciesBatchPersistenceService getSpeciesBatchPersistenceService() {
- return getPersistenceService("speciesBatchPersistenceService",
+ return getPersistenceService("batchPersistenceService",
SpeciesBatchPersistenceService.class);
}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/measure/MeasurementPersistenceHelper.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/measure/MeasurementPersistenceHelper.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/measure/MeasurementPersistenceHelper.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -206,6 +206,19 @@
return sortingMeasurement;
}
+
+ public SortingMeasurement getInheritedSortingMeasurement(
+ SortingBatch sortingBatch, Integer pmfmId) {
+ if (sortingBatch.getInheritedSortingMeasurements() != null) {
+ for (SortingMeasurement qm : sortingBatch
+ .getInheritedSortingMeasurements()) {
+ if (pmfmId.equals(qm.getPmfm().getId())) {
+ return qm;
+ }
+ }
+ }
+ return null;
+ }
public Integer sampleCategory2PmfmId(SampleCategoryEnum sampleCategory) {
Integer pmfmId = null;
Modified: trunk/tutti-persistence/src/main/resources/applicationContext-service-tutti.xml
===================================================================
--- trunk/tutti-persistence/src/main/resources/applicationContext-service-tutti.xml 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/applicationContext-service-tutti.xml 2013-02-14 15:27:16 UTC (rev 413)
@@ -53,8 +53,8 @@
<property name="diskExpiryThreadIntervalSeconds" value="300"/>
</bean>
- <bean id="tuttiPmfmsCache" parent="tuttiAbstractEternalCache">
- <property name="cacheName" value="pmfms" />
+ <bean id="tuttiBatchTreeCache" parent="tuttiAbstractCache">
+ <property name="cacheName" value="batchTree" />
</bean>
<!-- Eternal caches : -->
@@ -67,6 +67,10 @@
<property name="timeToIdle" value="0"/>
</bean>
+ <bean id="tuttiPmfmsCache" parent="tuttiAbstractEternalCache">
+ <property name="cacheName" value="pmfms" />
+ </bean>
+
<bean id="tuttiFishingVesselsCache" parent="tuttiAbstractEternalCache">
<property name="cacheName" value="fishingVessels" />
</bean>
Modified: trunk/tutti-persistence/src/main/resources/i18n/tutti-persistence_fr_FR.properties
===================================================================
--- trunk/tutti-persistence/src/main/resources/i18n/tutti-persistence_fr_FR.properties 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/i18n/tutti-persistence_fr_FR.properties 2013-02-14 15:27:16 UTC (rev 413)
@@ -12,4 +12,7 @@
tutti.option.persistence.jdbc.url.description=URL de connexion à la base de données
tutti.option.persistence.jdbc.username.description=Login de l'utilisateur pour se connecter à la base de données
tutti.option.persistence.protocol.directory.description=Répertoire où sont conservés les protocoles
+tutti.persistence.batch.validation.onlyTaxonButPmfmFound=Batch [id\=%s] should not have any sorting measurement (should only have a reference taxon), but found pmfm [id\=%s].
+tutti.persistence.batch.validation.pmfmNotFound=Batch [id\=%s] should have a sorting measurement with a pmfm id in %s or a length pmfm, but found pmfm [id\=%s].
+tutti.persistence.batch.validation.referenceTaxonNotFound=Batch [id\=%s] should have a reference taxon.
tutti.persistence.config=Configuration de la persistence de Tutti
Modified: trunk/tutti-persistence/src/main/resources/queries-override.hbm.xml
===================================================================
--- trunk/tutti-persistence/src/main/resources/queries-override.hbm.xml 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/queries-override.hbm.xml 2013-02-14 15:27:16 UTC (rev 413)
@@ -310,77 +310,6 @@
<query-param name="pmfmIdSortingType" type="java.lang.Integer"/>
</query>
- <query name="allSpeciesBatch">
- <![CDATA[
- SELECT
- b.id as batchId,
- b.individualCount AS individualCount,
- qm.numericalValue AS weight,
- b.samplingRatio AS samplingRatio,
- b.samplingRatioText AS samplingRatioText,
- b.comments AS comments,
- sm.pmfm.id AS pmfmId,
- sm.qualitativeValue.id as qvValue,
- sm.numericalValue AS numValue,
- sm.alphanumericalValue AS alphaValue,
- b.referenceTaxon.id as referenceTaxonId,
- b.parentBatch.id as parentBatchId
- FROM
- SortingBatchImpl b
- INNER JOIN b.rootBatch cb
- LEFT OUTER JOIN b.sortingMeasurements sm
- LEFT OUTER JOIN b.quantificationMeasurements qm
- WHERE
- cb.fishingOperation.id=:fishingOperationId
- AND (
- qm is null
- OR qm.isReferenceQuantification=true
- )
- ORDER BY b.id
- ]]>
- <query-param name="fishingOperationId" type="java.lang.Integer"/>
- </query>
-
- <query name="parentBatch">
- <![CDATA[
- SELECT
- b2.id as parentBatchId,
- cb.id as rootBatchId
- FROM
- CatchBatchImpl cb
- INNER JOIN cb.childBatchs b1
- INNER JOIN b1.childBatchs b2,
- SortingMeasurementImpl sm1,
- SortingMeasurementImpl sm2
- WHERE
- cb.fishingOperation.id = :fishingOperationId
- AND sm1.sortingBatch.id=b1.id
- AND sm1.pmfm.id=:pmfmIdSorted
- AND sm1.qualitativeValue.id=:qualitativeIdSorted
- AND sm2.sortingBatch.id=b2.id
- AND sm2.pmfm.id=:pmfmIdSortingType
- AND sm2.qualitativeValue.id=:qualitativeIdSortingType
- ]]>
- <query-param name="fishingOperationId" type="java.lang.Integer"/>
- <query-param name="pmfmIdSorted" type="java.lang.Integer"/>
- <query-param name="qualitativeIdSorted" type="java.lang.Integer"/>
- <query-param name="pmfmIdSortingType" type="java.lang.Integer"/>
- <query-param name="qualitativeIdSortingType" type="java.lang.Integer"/>
- </query>
-
- <query name="speciesBatchChildren">
- <![CDATA[
- SELECT
- cb.id
- FROM
- SortingBatchImpl b
- INNER JOIN b.childBatchs cb
- WHERE
- b.id = :batchId
- ]]>
- <query-param name="batchId" type="java.lang.Integer"/>
- </query>
-
<query name="updateBatchSpecies">
<![CDATA[
UPDATE SortingBatchImpl b
@@ -815,16 +744,6 @@
<!--<fetch-profile name="tutti">-->
<!--TODO Create fetch profile to avoid eager loading -->
<!--</fetch-profile>-->
-
- <fetch-profile name="batch-with-measurements">
- <fetch entity="BatchImpl" association="quantificationMeasurements" style="join"/>
- <fetch entity="CatchBatchImpl" association="quantificationMeasurements" style="join"/>
- <fetch entity="SortingBatchImpl" association="sortingMeasurements" style="join"/>
- <fetch entity="SortingBatchImpl" association="quantificationMeasurements" style="join"/>
- </fetch-profile>
- <fetch-profile name="batch-with-childs">
- <fetch entity="BatchImpl" association="childBatchs" style="join"/>
- </fetch-profile>
-
+
</hibernate-mapping>
Modified: trunk/tutti-persistence/src/main/resources/tutti-db-conf.properties
===================================================================
--- trunk/tutti-persistence/src/main/resources/tutti-db-conf.properties 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/tutti-db-conf.properties 2013-02-14 15:27:16 UTC (rev 413)
@@ -46,4 +46,6 @@
hibernate.generate_statistics=false
hibernate.query.substitutions=true 1, false 0
hibernate.hbm2ddl.auto=none
-hibernate.default_batch_fetch_size=1
\ No newline at end of file
+hibernate.default_batch_fetch_size=1
+adagio.cache.use_tree_cache=true
+ehcache.disk.store.dir=c:/temp/ehcache
\ No newline at end of file
Modified: trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties
===================================================================
--- trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties 2013-02-14 15:27:16 UTC (rev 413)
@@ -375,4 +375,10 @@
DepartmentId.UNKNOWN_RECORDER_DEPARTMENT=181
#TODO A creer (dans les enumerations Allegro)
-ProgramCode.SCIENTIFIC_CRUISE_PREFIX=CAM-
\ No newline at end of file
+ProgramCode.SCIENTIFIC_CRUISE_PREFIX=CAM-
+
+#Reference taxon correspondant à "Biota" (ou "Vie")
+ReferenceTaxonId.LIFE=7637
+#Reference taxon correspondant à "Non Biota" (ou "Non Vie" - matière inerte)
+# TODO : a creer dans la base harmonie et a�changer !
+ReferenceTaxonId.INERT=1
\ No newline at end of file
Added: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java (rev 0)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -0,0 +1,187 @@
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id: CatchBatchPersistenceServiceReadTest.java 379 2013-02-10 13:41:29Z tchemit $
+ * $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/test/j… $
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.Cruise;
+import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.springframework.dao.DataRetrievalFailureException;
+
+import com.google.common.collect.Maps;
+
+/**
+ * To test {@link CatchBatchPersistenceService} for read operation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class BatchPersistenceServiceReadTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.readDb();
+
+ protected BatchPersistenceService service;
+ protected FishingOperationPersistenceService fishingOperationService;
+ protected FishingOperation fishingOperation;
+
+ @Before
+ public void setUp() throws Exception {
+ service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
+ fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
+
+ List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
+ assertNotNull(fishingOperations);
+ assertTrue(fishingOperations.size() > 0);
+ fishingOperation = fishingOperations.get(0);
+ assertNotNull(fishingOperation);
+ assertNotNull(fishingOperation.getId());
+ }
+
+ @Test
+ public void getCatchBatchFromFishingOperation() throws Exception {
+
+ try {
+ CatchBatch catchBatch = service.getCatchBatchFromFishingOperation(fishingOperation.getId());
+ fail("batch tree must be invalid (old CGFS tree structure), for fishing operation id=" + fishingOperation.getId());
+ }
+ catch(DataRetrievalFailureException drfe) {
+ // success
+ }
+ }
+
+ @Test
+ public void getAllRootSpeciesBatch(/*String fishingOperationId*/) {
+ }
+
+ @Test
+ public void getAllSpeciesBatchFrequency(/*String speciesBatchId*/) {
+
+ }
+
+ public static void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
+ assertNotNull(actualBatch);
+ assertNotNull(actualBatch.getId());
+ if (assertIdEquals && expectedBatch.getId() != null) {
+ assertEquals(expectedBatch.getId(), actualBatch.getId());
+ }
+ assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
+ assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
+ if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
+ assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
+ actualBatch.getSampleCategoryValue());
+ assertEquals(
+ ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
+ ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
+ } else {
+ assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
+ }
+ assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
+ assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
+ assertEquals(expectedBatch.getComment(), actualBatch.getComment());
+
+ // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
+ // (Because getSpeciesBatch(id) could not always retrieve the species)
+ if (expectedBatch.getSpecies() != null && (
+ expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
+ || actualBatch.getSpecies() != null)) {
+ assertNotNull(actualBatch.getSpecies());
+ assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
+ }
+ }
+
+ public static void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
+ assertNotNull(actualFrequencies);
+ assertEquals(expectedFrequencies.size(), actualFrequencies.size());
+
+ // Store actual batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
+ expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ }
+
+ // Store expected batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
+ assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
+ actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ assertNotNull(speciesBatchFrequency.getId());
+ }
+
+ for (Float lengthStep : expectedLengthMap.keySet()) {
+ SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
+ SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
+ if (assertIdEquals) {
+ assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
+ }
+ assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
+ assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
+ assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
+ assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
+ assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
+ //assertNotNull(expectedBatchFrequency.getBatch());
+ //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
+ }
+ }
+
+ public static SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
+ return getSpeciesBatch(speciesBatchId, TuttiPersistenceServiceLocator.getBatchPersistenceService().getAllRootSpeciesBatch(fishingOperationId));
+ }
+
+ public static SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
+ if (speciesBatchs == null) {
+ return null;
+ }
+ for (SpeciesBatch speciesBatch : speciesBatchs) {
+ if (speciesBatchId.equals(speciesBatch.getId())) {
+ return speciesBatch;
+ }
+ if (speciesBatch.getChildBatchs() != null) {
+ speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
+ if (speciesBatch != null) {
+ return speciesBatch;
+ }
+ }
+ }
+ return null;
+ }
+
+}
Added: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java (rev 0)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -0,0 +1,621 @@
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id: CatchBatchPersistenceServiceWriteTest.java 379 2013-02-10 13:41:29Z tchemit $
+ * $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/test/j… $
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.Cruise;
+import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
+import fr.ifremer.tutti.persistence.entities.referential.Species;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.springframework.dao.DataRetrievalFailureException;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.*;
+
+/**
+ * To test {@link CatchBatchPersistenceService} for write operation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class BatchPersistenceServiceWriteTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.writeDb();
+
+ protected BatchPersistenceService service;
+
+ protected CruisePersistenceService cruiseService;
+
+ protected FishingOperationPersistenceService fishingOperationService;
+
+ protected CatchBatchPersistenceService catchBatchService;
+
+ protected ReferentialPersistenceService referentialService;
+
+ protected Cruise cruise;
+
+ protected FishingOperation fishingOperationNoCatchBatch;
+
+ protected FishingOperation fishingOperationWithEmptyBatch;
+
+ protected CatchBatch catchBacth;
+
+ protected List<Species> species;
+
+ protected Caracteristic sortedUnsortedPMFM;
+
+ protected CaracteristicQualitativeValue horsVracQualitativeValue;
+
+ protected CaracteristicQualitativeValue vracQualitativeValue;
+
+ protected Caracteristic maturityPMFM;
+
+ protected CaracteristicQualitativeValue firstMaturityQualitativeValue;
+
+ protected Caracteristic sexPMFM;
+
+ protected CaracteristicQualitativeValue maleQualitativeValue;
+
+ protected CaracteristicQualitativeValue femaleQualitativeValue;
+
+ protected CaracteristicQualitativeValue unkQualitativeValue;
+
+ protected Caracteristic frequencyPMFM;
+
+ @Before
+ public void setUp() throws Exception {
+ service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
+ cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService();
+ fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
+ catchBatchService = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService();
+ referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService();
+
+ species = referentialService.getAllSpecies();
+ assertNotNull(species);
+ assertTrue(species.size() > 2);
+
+ cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId());
+ cruise.setId(null);
+ Calendar calendar = new GregorianCalendar();
+ cruise.setBeginDate(calendar.getTime());
+ cruise.setYear(calendar.get(Calendar.YEAR));
+ calendar.add(Calendar.MONTH, 1); // add one month
+ cruise.setEndDate(calendar.getTime());
+ cruise = cruiseService.createCruise(cruise);
+
+ // Create a first operation, with no cacth batch : to test CatchBatch insert/update :
+ List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
+ assertNotNull(fishingOperations);
+ assertTrue(fishingOperations.size() > 0);
+ fishingOperationNoCatchBatch = fishingOperations.get(0);
+ fishingOperationNoCatchBatch = fishingOperationService.getFishingOperation(fishingOperationNoCatchBatch.getId());
+ fishingOperationNoCatchBatch.setId(null);
+ fishingOperationNoCatchBatch.setCruise(cruise);
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 1);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationNoCatchBatch.setGearShootingStartDate(calendar.getTime());
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 10);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationNoCatchBatch.setGearShootingEndDate(calendar.getTime());
+ fishingOperationNoCatchBatch = fishingOperationService.createFishingOperation(fishingOperationNoCatchBatch);
+
+ // Create a second operation, with no cacth batch : to test CatchBatch insert/update :
+ fishingOperationWithEmptyBatch = fishingOperations.get(1);
+ fishingOperationWithEmptyBatch = fishingOperationService.getFishingOperation(fishingOperationWithEmptyBatch.getId());
+ fishingOperationWithEmptyBatch.setId(null);
+ fishingOperationWithEmptyBatch.setCruise(cruise);
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 11);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationWithEmptyBatch.setGearShootingStartDate(calendar.getTime());
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 12);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationWithEmptyBatch.setGearShootingEndDate(calendar.getTime());
+ fishingOperationWithEmptyBatch = fishingOperationService.createFishingOperation(fishingOperationWithEmptyBatch);
+
+ catchBacth = new CatchBatch();
+ catchBacth.setFishingOperation(fishingOperationWithEmptyBatch);
+ catchBacth = catchBatchService.createCatchBatch(catchBacth);
+
+ sortedUnsortedPMFM = referentialService.getSortedUnsortedCaracteristic();
+ horsVracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(0);
+ vracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(1);
+ maturityPMFM = referentialService.getMaturityCaracteristic();
+ firstMaturityQualitativeValue = maturityPMFM.getQualitativeValue(0);
+ sexPMFM = referentialService.getSexCaracteristic();
+ maleQualitativeValue = sexPMFM.getQualitativeValue(1);
+ femaleQualitativeValue = sexPMFM.getQualitativeValue(2);
+ unkQualitativeValue = sexPMFM.getQualitativeValue(3);
+
+ List<Caracteristic> cara = referentialService.getAllCaracteristic();
+ for (Caracteristic caracteristic : cara) {
+ if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER
+ && caracteristic.getPrecision() != null
+ && caracteristic.getPrecision() == 0.5f) {
+ frequencyPMFM = caracteristic;
+ break;
+ }
+ }
+ assertNotNull("no numerical PMFM with a precision has been found. Could not define a PMFM for batch frequencies.", frequencyPMFM);
+
+ }
+
+ @Test
+ public void createAndSaveCatchBatch() throws Exception {
+ CatchBatch catchBatch;
+
+ catchBatch = new CatchBatch();
+ catchBatch.setFishingOperation(fishingOperationNoCatchBatch);
+
+ // -----------------------------------------------------------------------------
+ // 1. Test with only mandatory properties
+ // -----------------------------------------------------------------------------
+
+ // Create and reload (test round trip)
+ assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 2. Test with all properties
+ // -----------------------------------------------------------------------------
+ catchBatch.setId(null);
+ // total weight : 100kg
+ catchBatch.setCatchTotalWeight(75f);
+ // Vrac :
+ {
+ // note : poids trie par la balance tremis (thalassa) (init par pupitri)
+ catchBatch.setCatchTotalSortedTremisWeight(50f);
+ // note : poids vrac caroussel (thalassa) (init par pupitri) (vrac trie) ou bien "poids trié fournie par la table de tri (Sum(Si)
+ catchBatch.setCatchTotalSortedCarousselWeight(45f);
+
+ // Species
+ {
+ catchBatch.setSpeciesTotalSortedWeight(12f);
+ catchBatch.setSpeciesTotalSampleSortedWeight(8f);
+ catchBatch.setSpeciesTotalLivingNotItemizedWeight(0.2f);
+ catchBatch.setSpeciesTotalInertWeight(0.1f);
+ }
+ }
+ // Hors Vrac : 10kg
+ {
+ catchBatch.setCatchTotalUnsortedWeight(10f);
+
+ // Species
+ {
+ catchBatch.setSpeciesTotalUnsortedWeight(10f);
+ }
+ }
+ // Rejet : 15kg
+ catchBatch.setCatchTotalRejectedWeight(15f);
+
+ // Create and reload (test round trip)
+ assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 2. Test save after modification
+ // -----------------------------------------------------------------------------
+ catchBatch.setCatchTotalSortedTremisWeight(null);
+ catchBatch.setCatchTotalSortedCarousselWeight(null);
+ catchBatch.setSpeciesTotalSortedWeight(null);
+ catchBatch.setSpeciesTotalSampleSortedWeight(null);
+ catchBatch.setCatchTotalUnsortedWeight(null);
+ catchBatch.setSpeciesTotalUnsortedWeight(null);
+
+ assertSaveAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+ }
+
+ @Test
+ public void createAndSaveSpeciesBatchAndFrequencies() {
+ SpeciesBatch esp1Batch = null;
+ SpeciesBatch esp2Batch = null;
+ SpeciesBatch frequenciesParentBatch = null;
+ SpeciesBatch batch = null;
+ Species taxon1 = species.get(0);
+ Species taxon2 = species.get(1);
+
+ // -----------------------------------------------------------------------------
+ // 1. Test with only mandatory properties
+ // -----------------------------------------------------------------------------
+ // batch : "ESP1 - Vrac/5"
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setFishingOperation(fishingOperationNoCatchBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(5f);
+
+ assertCreateAndReloadSpeciesBatch(batch, null);
+
+ // Save ESP1 batch
+ esp1Batch = batch;
+
+ // -----------------------------------------------------------------------------
+ // 2. Test child "Male/2"
+ // -----------------------------------------------------------------------------
+ // Batch : ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp1Batch);
+ batch.setSpecies(taxon1);
+ batch.setComment("ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(maleQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ batch.setWeight(1f);
+ batch.setNumber(7);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 3. Test child "Female/2"
+ // -----------------------------------------------------------------------------
+ // Batch : ESP1 - Vrac/5 Female/3 Nombre/14
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp1Batch);
+ batch.setSpecies(taxon1);
+ batch.setComment("ESP1 - Vrac/5 Female/3 Nombre/14");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(femaleQualitativeValue);
+ batch.setSampleCategoryWeight(3f);
+ batch.setWeight(null);
+ batch.setNumber(14);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 4. Test : ESP2 - Vrac/7
+ // \- ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
+ // -----------------------------------------------------------------------------
+ // batch : "ESP2 - Vrac/7 "
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setSpecies(taxon2);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(7f);
+
+ assertCreateAndReloadSpeciesBatch(batch, null);
+ esp2Batch = batch;
+
+ // Batch : ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp2Batch);
+ batch.setSpecies(taxon2);
+ batch.setComment("ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11");
+ batch.setSampleCategoryType(SampleCategoryEnum.maturity);
+ batch.setSampleCategoryValue(firstMaturityQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ batch.setWeight(1f);
+ batch.setNumber(11);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 5. Test save after modifications
+ // -----------------------------------------------------------------------------
+ // Batch : ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99
+ batch.setComment("ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(unkQualitativeValue);
+ batch.setSampleCategoryWeight(1.75f);
+ batch.setWeight(1.11f);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setNumber(99);
+
+ // Save and reload, then check
+ SpeciesBatch savedBatch = service.saveSpeciesBatch(batch);
+ assertSpeciesBatch(savedBatch, batch, false);
+ SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), savedBatch.getId());
+ assertSpeciesBatch(savedBatch, reloadedBatch, true);
+
+ // Save batch for later
+ frequenciesParentBatch = batch;
+
+ // -----------------------------------------------------------------------------
+ // 6. Test change species
+ // -----------------------------------------------------------------------------
+ esp2Batch.setSpecies(taxon1);
+ service.changeSpeciesBatchSpecies(esp2Batch.getId(), taxon1);
+ assertSpeciesBatch(savedBatch, batch, false);
+ reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp2Batch.getId());
+ assertSpeciesBatch(esp2Batch, reloadedBatch, true);
+
+ // -----------------------------------------------------------------------------
+ // 7. Test get all root species
+ // -----------------------------------------------------------------------------
+ List<SpeciesBatch> rootSpeciesBatch = service.getAllRootSpeciesBatch(fishingOperationWithEmptyBatch.getId());
+ assertNotNull(rootSpeciesBatch);
+ assertEquals(2, rootSpeciesBatch.size());
+ assertNotNull(rootSpeciesBatch.get(0).getChildBatchs());
+ assertTrue(rootSpeciesBatch.get(0).getChildBatchs().size() > 0);
+ assertNotNull(rootSpeciesBatch.get(1).getChildBatchs());
+ assertTrue(rootSpeciesBatch.get(1).getChildBatchs().size() > 0);
+
+ // -----------------------------------------------------------------------------
+ // 8. Test batch frequency creation
+ // -----------------------------------------------------------------------------
+
+ List<SpeciesBatchFrequency> frequencies = Lists.newArrayList();
+ float lengthStep = 0.5f;
+ for (float length = lengthStep; length < lengthStep * 20; length += lengthStep) {
+ SpeciesBatchFrequency frequency = new SpeciesBatchFrequency();
+ frequency.setLengthStep(length);
+ frequency.setNumber((int) (length * 2));
+ frequency.setWeight(0.01f * length * 2);
+ frequency.setLengthStepCaracteristic(frequencyPMFM);
+ frequency.setBatch(frequenciesParentBatch);
+ frequency.setComment("comments");
+ frequencies.add(frequency);
+ }
+ List<SpeciesBatchFrequency> createdFrequencies = assertCreateAndReloadSpeciesBatchFrequency(frequencies, frequenciesParentBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 9. Test batch frequency update
+ // -----------------------------------------------------------------------------
+ // Update some batchs (1cm, 2cm, etc)
+ for (SpeciesBatchFrequency speciesBatchFrequency : createdFrequencies) {
+ float length = speciesBatchFrequency.getLengthStep();
+ if ((float) (int) length == length) {
+ speciesBatchFrequency.setNumber(12);
+ speciesBatchFrequency.setComment(null);
+ }
+ }
+ // And remove the last item (should be deleted in DB)
+ createdFrequencies.remove(createdFrequencies.size()-1);
+ List<SpeciesBatchFrequency> savedFrequencies = service.saveSpeciesBatchFrequency(frequenciesParentBatch.getId(), frequencies);
+ assertBatchFrequencies(createdFrequencies, savedFrequencies, true);
+ }
+
+ @Test
+ public void deleteSpeciesBatch(/*String id*/) {
+ SpeciesBatch esp1Batch;
+ SpeciesBatch batch;
+ Species taxon1 = species.get(0);
+
+ // -----------------------------------------------------------------------------
+ // 1. Create two batchs (parent + child), then remove the parent batch
+ // -----------------------------------------------------------------------------
+ // batch : ESP1 Vrac/5
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(5f);
+ assertCreateAndReloadSpeciesBatch(batch, null);
+ esp1Batch = batch;
+
+ // batch : ESP1 Vrac/5 Male/2
+ batch = new SpeciesBatch();
+ batch.setParentBatch(esp1Batch);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(maleQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ assertCreateAndReloadSpeciesBatch(batch, esp1Batch.getId());
+
+ // Try to remove
+ service.deleteSpeciesBatch(esp1Batch.getId());
+
+ // Check if remove
+ try {
+ batch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp1Batch.getId());
+ assertNull(batch);
+ } catch (DataRetrievalFailureException drfe) {
+ assertNotNull(drfe);
+ }
+ }
+
+ protected void assertCreateAndReloadSpeciesBatch(SpeciesBatch batch, String parentBatchId) {
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+
+ // Create batch
+ SpeciesBatch createdBatch = service.createSpeciesBatch(batch, parentBatchId);
+ assertSpeciesBatch(batch, createdBatch, false);
+
+ // then reload (for round trip check)
+ SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), createdBatch.getId());
+ if (parentBatchId == null) {
+ assertNull(reloadedBatch.getParentBatch());
+ } else {
+ assertNotNull(reloadedBatch.getParentBatch());
+ assertEquals(parentBatchId, reloadedBatch.getParentBatch().getId());
+ }
+ assertSpeciesBatch(createdBatch, reloadedBatch, false);
+
+ batch.setId(createdBatch.getId());
+ }
+
+ protected void assertCreateAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
+ CatchBatch createdCatchBatch = service.createCatchBatch(catchBatch);
+ assertNotNull(createdCatchBatch);
+ assertNotNull(createdCatchBatch.getId());
+ assertCatchBatch(catchBatch, createdCatchBatch, false);
+
+ CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
+ assertCatchBatch(createdCatchBatch, reloadedCatchBatch, true);
+
+ catchBatch.setId(createdCatchBatch.getId());
+ }
+
+ protected void assertSaveAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
+ CatchBatch savedCatchBatch = service.saveCatchBatch(catchBatch);
+ assertNotNull(savedCatchBatch);
+ assertNotNull(savedCatchBatch.getId());
+ assertCatchBatch(catchBatch, savedCatchBatch, false);
+
+ CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
+ assertCatchBatch(savedCatchBatch, reloadedCatchBatch, true);
+ }
+
+ protected void assertCatchBatch(CatchBatch expectedCatchBatch,CatchBatch actualCatchBatch, boolean assertIdEquals) {
+ if (expectedCatchBatch == null) {
+ assertNull(actualCatchBatch);
+ return;
+ }
+
+ assertNotNull(actualCatchBatch);
+ if (assertIdEquals) {
+ assertEquals(expectedCatchBatch.getId(), actualCatchBatch.getId());
+ }
+ assertEquals(expectedCatchBatch.getCatchTotalWeight(), actualCatchBatch.getCatchTotalWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalSortedCarousselWeight(), actualCatchBatch.getCatchTotalSortedCarousselWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalSortedTremisWeight(), actualCatchBatch.getCatchTotalSortedTremisWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalUnsortedWeight(), actualCatchBatch.getCatchTotalUnsortedWeight());
+
+ assertEquals(expectedCatchBatch.getSpeciesTotalSampleSortedWeight(), actualCatchBatch.getSpeciesTotalSampleSortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalSortedWeight(), actualCatchBatch.getSpeciesTotalSortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalUnsortedWeight(), actualCatchBatch.getSpeciesTotalUnsortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalInertWeight(), actualCatchBatch.getSpeciesTotalInertWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalLivingNotItemizedWeight(), actualCatchBatch.getSpeciesTotalLivingNotItemizedWeight());
+ }
+
+ protected void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
+ assertNotNull(actualBatch);
+ assertNotNull(actualBatch.getId());
+ if (assertIdEquals && expectedBatch.getId() != null) {
+ assertEquals(expectedBatch.getId(), actualBatch.getId());
+ }
+ assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
+ assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
+ if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
+ assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
+ actualBatch.getSampleCategoryValue());
+ assertEquals(
+ ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
+ ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
+ } else {
+ assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
+ }
+ assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
+ assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
+ assertEquals(expectedBatch.getComment(), actualBatch.getComment());
+
+ // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
+ // (Because getSpeciesBatch(id) could not always retrieve the species)
+ if (expectedBatch.getSpecies() != null && (
+ expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
+ || actualBatch.getSpecies() != null)) {
+ assertNotNull(actualBatch.getSpecies());
+ assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
+ }
+ }
+ protected List<SpeciesBatchFrequency> assertCreateAndReloadSpeciesBatchFrequency(List<SpeciesBatchFrequency> frequencies, String parentBatchId) {
+
+ // Create batch
+ List<SpeciesBatchFrequency> createdFrequencies = service.saveSpeciesBatchFrequency(parentBatchId, frequencies);
+ assertBatchFrequencies(frequencies, createdFrequencies, false);
+
+ // then reload (for round trip check)
+ List<SpeciesBatchFrequency> reloadedFrequencies = service.getAllSpeciesBatchFrequency(parentBatchId);
+ assertBatchFrequencies(createdFrequencies, reloadedFrequencies, true);
+
+ return createdFrequencies;
+ }
+
+ protected void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
+ assertNotNull(actualFrequencies);
+ assertEquals(expectedFrequencies.size(), actualFrequencies.size());
+
+ // Store actual batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
+ expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ }
+
+ // Store expected batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
+ assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
+ actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ assertNotNull(speciesBatchFrequency.getId());
+ }
+
+ for (Float lengthStep : expectedLengthMap.keySet()) {
+ SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
+ SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
+ if (assertIdEquals) {
+ assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
+ }
+ assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
+ assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
+ assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
+ assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
+ assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
+ //assertNotNull(expectedBatchFrequency.getBatch());
+ //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
+ }
+ }
+
+ protected SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
+ return getSpeciesBatch(speciesBatchId, service.getAllRootSpeciesBatch(fishingOperationId));
+ }
+
+ protected SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
+ if (speciesBatchs == null) {
+ return null;
+ }
+ for (SpeciesBatch speciesBatch : speciesBatchs) {
+ if (speciesBatchId.equals(speciesBatch.getId())) {
+ return speciesBatch;
+ }
+ if (speciesBatch.getChildBatchs() != null) {
+ speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
+ if (speciesBatch != null) {
+ return speciesBatch;
+ }
+ }
+ }
+ return null;
+ }
+}
1
0
r412 - trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro
by tchemit@users.forge.codelutin.com 14 Feb '13
by tchemit@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: tchemit
Date: 2013-02-14 11:40:25 +0100 (Thu, 14 Feb 2013)
New Revision: 412
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/412
Log:
improve synchro model
Modified:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 08:42:09 UTC (rev 411)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 10:40:25 UTC (rev 412)
@@ -28,7 +28,7 @@
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
-import org.apache.commons.lang.time.DateUtils;
+import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.dialect.Dialect;
@@ -121,6 +121,28 @@
if (result.isSuccess()) {
+ // prepare model (compute update date, count rows to update,...)
+
+ for (TuttiTable tuttiTable : TuttiTable.values()) {
+
+ String tableName = tuttiTable.name();
+
+ TuttiTableMetadata table = remoteMeta.getTable(tableName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Prepare table: " + tableName);
+ }
+ prepareTable(table,
+ localConnection,
+ remoteConnection,
+ result);
+ }
+
+ long totalRows = result.getTotalRows();
+ if (log.isInfoEnabled()) {
+ log.info("Total rows to update: " + totalRows);
+ }
+
// prepare target (desactivate constraints)
prepareSynch(localConnection);
@@ -140,6 +162,14 @@
remoteConnection,
result);
}
+ if (log.isInfoEnabled()) {
+ long totalInserts = result.getTotalInserts();
+ long totalUpdates = result.getTotalUpdates();
+ log.info("Total rows to treat: " + totalRows);
+ log.info("Total rows inserted: " + totalInserts);
+ log.info("Total rows updated: " + totalUpdates);
+ log.info("Total rows treated: " + (totalInserts + totalUpdates));
+ }
} finally {
releaseSynch(localConnection);
}
@@ -231,9 +261,9 @@
* if table does not use a updateDate columns or if there
* is no data in table.
*/
- public Date getLastUpdateDate(Connection connection,
- TuttiTableMetadata table) throws SQLException {
- Date result = null;
+ public Timestamp getLastUpdateDate(Connection connection,
+ TuttiTableMetadata table) throws SQLException {
+ Timestamp result = null;
if (table.isWithUpdateDateColumn()) {
@@ -356,6 +386,7 @@
int columnCount = table.getColumnsCount();
String tableName = table.getName();
+ String tablePrefix = getTablePrefix(table) + " - " + result.getNbRows(tableName);
int[] pkIndex = table.getPkIndexs();
@@ -370,7 +401,6 @@
int countR = 0;
int insertCount = 0;
int updateCount = 0;
- int nbRowsToTreat = result.getNbRows(tableName);
while (incomingData.next()) {
List<String> pk = getPk(incomingData, pkIndex);
@@ -410,7 +440,7 @@
if (log.isDebugEnabled()) {
String pkAsString = pk.toString();
- log.debug(String.format("[%s] Execute query %s (pk:%s)", tableName, sql, pkAsString));
+ log.debug(String.format("%s Execute query %s (pk:%s)", tablePrefix, sql, pkAsString));
}
statement.addBatch();
@@ -427,7 +457,7 @@
}
if (countR % 10000 == 0) {
if (log.isInfoEnabled()) {
- log.info(String.format("[%s-%s] Rows Done: %s (inserts: %s, updates: %s)", tableName, nbRowsToTreat, countR, insertCount, updateCount));
+ log.info(String.format("%s Done: %s (inserts: %s, updates: %s)", tablePrefix, countR, insertCount, updateCount));
}
}
}
@@ -436,7 +466,7 @@
result.addInserts(tableName, insertCount);
result.addUpdates(tableName, updateCount);
if (log.isInfoEnabled()) {
- log.info(String.format("[%s-%s] Rows Done: %s (inserts: %s, updates: %s)", tableName, nbRowsToTreat, countR, insertCount, updateCount));
+ log.info(String.format("%s done: %s (inserts: %s, updates: %s)", tablePrefix, countR, insertCount, updateCount));
}
if (insertCount > 0 && insertCount % 1000 != 0) {
@@ -447,35 +477,29 @@
}
if (log.isDebugEnabled()) {
- log.debug(String.format("[%s] INSERT count: %s", tableName, result.getNbInserts(tableName)));
- log.debug(String.format("[%s] UPDATE count: %s", tableName, result.getNbUpdates(tableName)));
+ log.debug(String.format("%s INSERT count: %s", tablePrefix, result.getNbInserts(tableName)));
+ log.debug(String.format("%s UPDATE count: %s", tablePrefix, result.getNbUpdates(tableName)));
}
}
+ protected String getTablePrefix(TuttiTableMetadata table) {
+ return "[" + table.getName() + "(" + ReferentialSynchronizeHelper.IS_ASSOCIATION_TABLE.apply(table) + ")]";
+
+ }
+
public void synchronizeTable(TuttiTableMetadata table,
Connection localConnection,
Connection remoteConnection,
ReferentialSynchronizeResult result) throws SQLException {
- // get last updateDate used by local db
- Date updateDate = getLastUpdateDate(localConnection, table);
-
- if (updateDate != null) {
-
- // just inscrements of 1 milisecond to not having same
- updateDate = new Timestamp(DateUtils.setMilliseconds(updateDate, 0).getTime());
- updateDate = new Timestamp(DateUtils.addSeconds(updateDate, 1).getTime());
- }
String tableName = table.getName();
- long countToUpdate =
- getCountDataToUpdate(remoteConnection, table, updateDate);
+ String tablePrefix = getTablePrefix(table);
- if (log.isInfoEnabled()) {
- log.info(String.format("[%s] count to update: %s", tableName, countToUpdate));
- }
+ // get last updateDate used by local db
+ Date updateDate = result.getUpdateDate(tableName);
- result.addRows(tableName, (int) countToUpdate);
+ long countToUpdate = result.getNbRows(tableName);
if (countToUpdate > 0) {
@@ -490,7 +514,6 @@
// there is some data to update
-
TuttiTable tuttiTable = TuttiTable.valueOf(tableName);
if (tuttiTable.isAssociation()) {
PreparedStatement deleteStatement =
@@ -498,7 +521,7 @@
"DELETE FROM " + tableName);
deleteStatement.execute();
if (log.isInfoEnabled()) {
- log.info("Delete from association: " + tableName);
+ log.info(tablePrefix + " Delete association table");
}
}
@@ -506,7 +529,7 @@
Set<List<String>> existingIds = getExistingPrimaryKeys(localConnection, table);
if (log.isInfoEnabled()) {
- log.info("[" + tableName + "] existingIds: " + existingIds.size());
+ log.info(tablePrefix + " existingIds: " + existingIds.size());
}
// update table content
@@ -525,6 +548,36 @@
}
+ public void prepareTable(TuttiTableMetadata table,
+ Connection localConnection,
+ Connection remoteConnection,
+ ReferentialSynchronizeResult result) throws SQLException {
+
+ String tablePrefix = getTablePrefix(table);
+
+ String tableName = table.getName();
+
+ // get last updateDate used by local db
+ Timestamp updateDate = getLastUpdateDate(localConnection, table);
+
+ if (updateDate != null) {
+
+ // just inscrements of 1 milisecond to not having same
+ updateDate = new Timestamp(DateUtils.setMilliseconds(updateDate, 0).getTime());
+ updateDate = new Timestamp(DateUtils.addSeconds(updateDate, 1).getTime());
+ }
+
+ long countToUpdate =
+ getCountDataToUpdate(remoteConnection, table, updateDate);
+
+ if (log.isInfoEnabled()) {
+ log.info(String.format("%s nb rows to update: %s", tablePrefix, countToUpdate));
+ }
+
+ result.setUpdateDate(tableName, updateDate);
+ result.addRows(tableName, (int) countToUpdate);
+ }
+
public static void prepareSynch(Connection connection) throws SQLException {
PreparedStatement statement = connection.prepareStatement("SET REFERENTIAL_INTEGRITY FALSE;");
statement.executeUpdate();
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 08:42:09 UTC (rev 411)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 10:40:25 UTC (rev 412)
@@ -28,6 +28,7 @@
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+import java.sql.Timestamp;
import java.util.Map;
import java.util.Set;
@@ -63,6 +64,13 @@
protected final Map<String, Integer> updateHits = Maps.newTreeMap();
/**
+ * timestamp of last update date (per table).
+ *
+ * @since 1.0
+ */
+ protected final Map<String, Timestamp> updateDateHits = Maps.newTreeMap();
+
+ /**
* All table treated.
*
* @since 1.0
@@ -94,6 +102,30 @@
return ImmutableSet.copyOf(tableNames);
}
+ public long getTotalRows() {
+ long result = 0;
+ for (Integer nb : rowHits.values()) {
+ result += nb;
+ }
+ return result;
+ }
+
+ public long getTotalInserts() {
+ long result = 0;
+ for (Integer nb : insertHits.values()) {
+ result += nb;
+ }
+ return result;
+ }
+
+ public long getTotalUpdates() {
+ long result = 0;
+ for (Integer nb : updateHits.values()) {
+ result += nb;
+ }
+ return result;
+ }
+
public int getNbRows(String tableName) {
Integer result = rowHits.get(tableName);
if (result == null) {
@@ -136,6 +168,14 @@
}
}
+ public Timestamp getUpdateDate(String tableName) {
+ return updateDateHits.get(tableName);
+ }
+
+ public void setUpdateDate(String tableName, Timestamp t) {
+ updateDateHits.put(tableName, t);
+ }
+
public void addTableName(String tableName) {
tableNames.add(tableName);
}
1
0
r411 - in trunk/tutti-persistence/src: main/java/fr/ifremer/tutti/persistence/service/synchro test/java/fr/ifremer/tutti/persistence test/java/fr/ifremer/tutti/persistence/service/synchro
by tchemit@users.forge.codelutin.com 14 Feb '13
by tchemit@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: tchemit
Date: 2013-02-14 09:42:09 +0100 (Thu, 14 Feb 2013)
New Revision: 411
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/411
Log:
refs #1874: [IMP/EXP] - Synchronisation de r?\195?\169f?\195?\169rentiel (am?\195?\169lioration des logs+ ajout requete pour compter ce qu'il faut mettre ?\195?\160 jour)
Added:
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java
Modified:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiEntityTableMetadata.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-13 21:48:46 UTC (rev 410)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -28,6 +28,7 @@
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
+import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.dialect.Dialect;
@@ -40,6 +41,7 @@
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Properties;
@@ -94,25 +96,25 @@
TuttiEntities.getUrl(localProperties),
TuttiEntities.getUrl(remoteProperties));
- Connection targetConnection = null;
- Connection synchConnection = null;
+ Connection localConnection = null;
+ Connection remoteConnection = null;
try {
// create local connection
- targetConnection = TuttiEntities.createConnection(localProperties);
+ localConnection = TuttiEntities.createConnection(localProperties);
// create remote Connection
- synchConnection = TuttiEntities.createConnection(remoteProperties);
+ remoteConnection = TuttiEntities.createConnection(remoteProperties);
// load metas
- TuttiDatabaseMetadata targetMeta =
- loadDatabaseMetadata(targetConnection, dialect);
- TuttiDatabaseMetadata synchMeta =
- loadDatabaseMetadata(synchConnection, dialect);
+ TuttiDatabaseMetadata localMeta =
+ loadDatabaseMetadata(localConnection, dialect);
+ TuttiDatabaseMetadata remoteMeta =
+ loadDatabaseMetadata(remoteConnection, dialect);
// check schema
try {
- checkSchemas(targetMeta, synchMeta);
+ checkSchemas(localMeta, remoteMeta);
} catch (DataRetrievalFailureException e) {
result.setError(e);
}
@@ -120,7 +122,7 @@
if (result.isSuccess()) {
// prepare target (desactivate constraints)
- prepareSynch(targetConnection);
+ prepareSynch(localConnection);
try {
@@ -128,26 +130,26 @@
String tableName = tuttiTable.name();
- TuttiTableMetadata table = synchMeta.getTable(tableName);
+ TuttiTableMetadata table = remoteMeta.getTable(tableName);
if (log.isInfoEnabled()) {
log.info("Synchronize table: " + tableName);
}
synchronizeTable(table,
- targetConnection,
- synchConnection,
+ localConnection,
+ remoteConnection,
result);
}
} finally {
- releaseSynch(synchConnection);
+ releaseSynch(localConnection);
}
- targetConnection.commit();
+ localConnection.commit();
}
} catch (SQLException e) {
try {
- if (targetConnection != null) {
- targetConnection.rollback();
+ if (localConnection != null) {
+ localConnection.rollback();
}
} catch (SQLException e1) {
@@ -155,8 +157,8 @@
}
result.setError(e);
} finally {
- JdbcUtils.closeConnection(synchConnection);
- JdbcUtils.closeConnection(targetConnection);
+ JdbcUtils.closeConnection(remoteConnection);
+ JdbcUtils.closeConnection(localConnection);
}
return result;
}
@@ -241,7 +243,7 @@
try {
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
- result = resultSet.getDate(1);
+ result = resultSet.getTimestamp(1);
}
statement.close();
} finally {
@@ -263,7 +265,7 @@
if (table.useUpdateDateColumn() &&
table.isWithUpdateDateColumn() &&
fromDate != null) {
- statement.setDate(1, new java.sql.Date(fromDate.getTime()));
+ statement.setTimestamp(1, new Timestamp(fromDate.getTime()));
}
statement.setFetchSize(1000);
@@ -271,6 +273,27 @@
return result;
}
+ public long getCountDataToUpdate(Connection connection,
+ TuttiTableMetadata table,
+ Date fromDate) throws SQLException {
+
+ String sql = fromDate == null ?
+ table.getCountDataToUpdateQueryWithNull() :
+ table.getCountDataToUpdateQuery();
+
+ PreparedStatement statement = connection.prepareStatement(sql);
+ if (table.useUpdateDateColumn() &&
+ table.isWithUpdateDateColumn() &&
+ fromDate != null) {
+ statement.setTimestamp(1, new Timestamp(fromDate.getTime()));
+ }
+
+ ResultSet queryResult = statement.executeQuery();
+ queryResult.next();
+ long result = queryResult.getLong(1);
+ return result;
+ }
+
public Set<List<String>> getExistingPrimaryKeys(Connection connection,
TuttiTableMetadata table) throws SQLException {
@@ -347,7 +370,8 @@
int countR = 0;
int insertCount = 0;
int updateCount = 0;
- do {
+ int nbRowsToTreat = result.getNbRows(tableName);
+ while (incomingData.next()) {
List<String> pk = getPk(incomingData, pkIndex);
@@ -403,16 +427,16 @@
}
if (countR % 10000 == 0) {
if (log.isInfoEnabled()) {
- log.info("Rows Done: " + countR);
+ log.info(String.format("[%s-%s] Rows Done: %s (inserts: %s, updates: %s)", tableName, nbRowsToTreat, countR, insertCount, updateCount));
}
}
}
- while (incomingData.next());
+
result.addInserts(tableName, insertCount);
result.addUpdates(tableName, updateCount);
if (log.isInfoEnabled()) {
- log.info("Rows Done: " + countR);
+ log.info(String.format("[%s-%s] Rows Done: %s (inserts: %s, updates: %s)", tableName, nbRowsToTreat, countR, insertCount, updateCount));
}
if (insertCount > 0 && insertCount % 1000 != 0) {
@@ -436,26 +460,37 @@
// get last updateDate used by local db
Date updateDate = getLastUpdateDate(localConnection, table);
- if (log.isInfoEnabled()) {
- log.info("[" + table.getName() + "] updateDate: " + updateDate);
+ if (updateDate != null) {
+
+ // just inscrements of 1 milisecond to not having same
+ updateDate = new Timestamp(DateUtils.setMilliseconds(updateDate, 0).getTime());
+ updateDate = new Timestamp(DateUtils.addSeconds(updateDate, 1).getTime());
}
+ String tableName = table.getName();
- // get data to synch
- ResultSet dataToUpdate = getDataToUpdate(remoteConnection,
- table,
- updateDate);
+ long countToUpdate =
+ getCountDataToUpdate(remoteConnection, table, updateDate);
if (log.isInfoEnabled()) {
- log.info("[" + table.getName() + "] dataToUpdate: " + dataToUpdate);
+ log.info(String.format("[%s] count to update: %s", tableName, countToUpdate));
}
- try {
- if (dataToUpdate.next()) {
+ result.addRows(tableName, (int) countToUpdate);
+
+ if (countToUpdate > 0) {
+
+ // there is some row to update
+
+ // get data to synch
+ ResultSet dataToUpdate = getDataToUpdate(remoteConnection,
+ table,
+ updateDate);
+
+ try {
+
// there is some data to update
- String tableName = table.getName();
-
TuttiTable tuttiTable = TuttiTable.valueOf(tableName);
if (tuttiTable.isAssociation()) {
PreparedStatement deleteStatement =
@@ -470,9 +505,8 @@
// gets existing ids in the target db
Set<List<String>> existingIds = getExistingPrimaryKeys(localConnection, table);
-
if (log.isInfoEnabled()) {
- log.info("[" + table.getName() + "] existingIds: " + existingIds.size());
+ log.info("[" + tableName + "] existingIds: " + existingIds.size());
}
// update table content
@@ -481,12 +515,14 @@
existingIds,
dataToUpdate,
result);
+
+ dataToUpdate.close();
+ } finally {
+ JdbcUtils.closeResultSet(dataToUpdate);
}
- dataToUpdate.close();
- } finally {
- JdbcUtils.closeResultSet(dataToUpdate);
}
+
}
public static void prepareSynch(Connection connection) throws SQLException {
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-13 21:48:46 UTC (rev 410)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -41,10 +41,32 @@
protected Exception error;
+ /**
+ * Number of rows detected to update (per table).
+ *
+ * @since 1.0
+ */
+ protected final Map<String, Integer> rowHits = Maps.newTreeMap();
+
+ /**
+ * Number of insert done (per table).
+ *
+ * @since 1.0
+ */
protected final Map<String, Integer> insertHits = Maps.newTreeMap();
+ /**
+ * Number of update done (per table).
+ *
+ * @since 1.0
+ */
protected final Map<String, Integer> updateHits = Maps.newTreeMap();
+ /**
+ * All table treated.
+ *
+ * @since 1.0
+ */
protected final Set<String> tableNames = Sets.newHashSet();
protected final String localUrl;
@@ -72,6 +94,14 @@
return ImmutableSet.copyOf(tableNames);
}
+ public int getNbRows(String tableName) {
+ Integer result = rowHits.get(tableName);
+ if (result == null) {
+ result = 0;
+ }
+ return result;
+ }
+
public int getNbInserts(String tableName) {
Integer result = insertHits.get(tableName);
if (result == null) {
@@ -88,12 +118,22 @@
return result;
}
+ public void addRows(String tableName, int nb) {
+ if (nb > 0) {
+ rowHits.put(tableName, getNbRows(tableName) + nb);
+ }
+ }
+
public void addUpdates(String tableName, int nb) {
- updateHits.put(tableName, getNbUpdates(tableName) + nb);
+ if (nb > 0) {
+ updateHits.put(tableName, getNbUpdates(tableName) + nb);
+ }
}
public void addInserts(String tableName, int nb) {
- insertHits.put(tableName, getNbInserts(tableName) + nb);
+ if (nb > 0) {
+ insertHits.put(tableName, getNbInserts(tableName) + nb);
+ }
}
public void addTableName(String tableName) {
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java 2013-02-13 21:48:46 UTC (rev 410)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -38,6 +38,8 @@
*/
public class TuttiAssociationTableMetadata extends TuttiTableMetadata {
+ private final String countDataToUpdateQuery;
+
private final String dataToUpdateQuery;
public TuttiAssociationTableMetadata(TableMetadata delegate,
@@ -55,6 +57,7 @@
query.append(" FROM ").append(getName());
dataToUpdateQuery = query.toString();
+ countDataToUpdateQuery = "SELECT count(*) FROM " + getName();
}
@Override
@@ -68,6 +71,16 @@
}
@Override
+ public String getCountDataToUpdateQuery() {
+ return countDataToUpdateQuery;
+ }
+
+ @Override
+ public String getCountDataToUpdateQueryWithNull() {
+ return countDataToUpdateQuery;
+ }
+
+ @Override
public boolean useUpdateDateColumn() {
return false;
}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiEntityTableMetadata.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiEntityTableMetadata.java 2013-02-13 21:48:46 UTC (rev 410)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiEntityTableMetadata.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -39,7 +39,12 @@
*/
public class TuttiEntityTableMetadata extends TuttiTableMetadata {
+ private final String countDataToUpdateQuery;
+
+ private final String countDataToUpdateQueryWithNull;
+
private final String dataToUpdateQuery;
+
private final String dataToUpdateQueryWithNull;
public TuttiEntityTableMetadata(TableMetadata delegate,
@@ -57,14 +62,20 @@
query.append(queryParams.substring(2));
query.append(" FROM ").append(getName());
- dataToUpdateQueryWithNull= query.toString();
+ dataToUpdateQueryWithNull = query.toString();
+ countDataToUpdateQueryWithNull = "SELECT count(*) FROM " + getName();
+ String whereClause;
+
if (isWithUpdateDateColumn()) {
// add a filter
- query.append(" WHERE (update_date IS NULL OR update_date > ?)");
+ whereClause = " WHERE (update_date IS NULL OR update_date > ?)";
+ } else {
+ whereClause = "";
}
- dataToUpdateQuery = query.toString();
+ dataToUpdateQuery = dataToUpdateQueryWithNull + whereClause;
+ countDataToUpdateQuery = countDataToUpdateQueryWithNull + whereClause;
}
@Override
@@ -78,6 +89,16 @@
}
@Override
+ public String getCountDataToUpdateQuery() {
+ return countDataToUpdateQuery;
+ }
+
+ @Override
+ public String getCountDataToUpdateQueryWithNull() {
+ return countDataToUpdateQueryWithNull;
+ }
+
+ @Override
public boolean useUpdateDateColumn() {
return true;
}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java 2013-02-13 21:48:46 UTC (rev 410)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -93,8 +93,10 @@
protected final boolean withUpdateDateColumn;
+ public abstract String getCountDataToUpdateQueryWithNull();
public abstract String getDataToUpdateQueryWithNull();
+ public abstract String getCountDataToUpdateQuery();
public abstract String getDataToUpdateQuery();
public abstract boolean useUpdateDateColumn();
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java 2013-02-13 21:48:46 UTC (rev 410)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -150,9 +150,12 @@
};
}
+ Class<?> testClass;
+
protected void before(Description description) throws Throwable {
- Class<?> testClass = description.getTestClass();
+ testClass = description.getTestClass();
+
File db = new File("src/test/db");
if (!db.exists()) {
@@ -195,7 +198,7 @@
config = new TuttiPersistenceConfig(applicationConfig);
if (writeDb) {
- FileUtils.copyDirectory(db, config.getDbDirectory());
+ copyDb(config.getDbDirectory(), !writeDb, null);
}
// load db config
@@ -211,10 +214,10 @@
if (writeDb) {
- p.setProperty("readonly", "false");
- BufferedWriter writer = Files.newWriter(dbConfig, Charsets.UTF_8);
- p.store(writer, "");
- writer.close();
+ // make sure db is on readonly mode
+ String readonly = p.getProperty("readonly");
+ Preconditions.checkNotNull(readonly, "Could not find readonly property on db confg: " + dbConfig);
+ Preconditions.checkState("false".equals(readonly), "readonly property must be at false value in write mode test in db confg: " + dbConfig);
} else {
// make sure db is on readonly mode
String readonly = p.getProperty("readonly");
@@ -241,17 +244,73 @@
}
}
+ protected final Set<File> toDetroy = Sets.newHashSet();
+
+ public void addToDestroy(File dir) {
+ toDetroy.add(dir);
+ }
+
+ public void copyDb(String dbDirectory, boolean readonly, Properties p) throws IOException {
+ File externalDbFile = getResourceDirectory(dbDirectory);
+ copyDb(externalDbFile, readonly, p);
+ }
+
+ public void copyDb(File target, boolean readonly, Properties p) throws IOException {
+ File db = new File("src/test/db");
+ if (!db.exists()) {
+
+ if (log.isWarnEnabled()) {
+ log.warn("Could not find db at " + db + ", test [" +
+ testClass + "] is skipped.");
+ }
+ Assume.assumeTrue(false);
+ }
+ toDetroy.add(target);
+ FileUtils.copyDirectory(db, target);
+ if (p != null) {
+ TuttiEntities.fillConnectionProperties(
+ p,
+ "jdbc:hsqldb:file:" + target.getAbsolutePath() + "/" + config.getDbName(),
+ config.getJdbcUsername(),
+ config.getJdbcPassword());
+ }
+
+ // load db config
+ File dbConfig = new File(target, config.getDbName() + ".properties");
+ Properties dbconf = new Properties();
+ BufferedReader reader = Files.newReader(dbConfig, Charsets.UTF_8);
+ dbconf.load(reader);
+ reader.close();
+
+ // switch readonly flag according to the write parameter
+ dbconf.setProperty("readonly", String.valueOf(readonly));
+ BufferedWriter writer = Files.newWriter(dbConfig, Charsets.UTF_8);
+ dbconf.store(writer, "");
+ writer.close();
+
+ }
+
protected void after(Description description) throws IOException {
- Class<?> testClass = description.getTestClass();
if (log.isInfoEnabled()) {
log.info("After test " + testClass);
}
- if (writeDb && !witherror) {
- if (log.isInfoEnabled()) {
- log.info("Remove copy db at: " + config.getDbDirectory());
+ if (!witherror) {
+ for (File file : toDetroy) {
+ if (file.exists()) {
+ if (log.isInfoEnabled()) {
+ log.info("Destroy directory: " + file);
+ }
+ try {
+ FileUtils.deleteDirectory(file);
+ } catch (IOException e) {
+ if (log.isErrorEnabled()) {
+ log.error("Could not delete directory: " + file, e);
+ }
+ }
+ }
}
- FileUtils.deleteDirectory(config.getDbDirectory());
+
}
// push back old classLoader
if (oldClassLoader != null) {
@@ -317,6 +376,7 @@
if (log.isInfoEnabled()) {
log.info("Create new db at " + directory);
}
+ addToDestroy(directory);
String jdbcUrl = "jdbc:hsqldb:file:" + directory.getAbsolutePath() + "/" + dbName;
String user = "SA";
String password = "";
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java 2013-02-13 21:48:46 UTC (rev 410)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -36,6 +36,7 @@
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
+import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
@@ -403,6 +404,8 @@
}
}
+ // To long some association tables
+ @Ignore
@Test
public void updateTable() throws SQLException, IOException {
@@ -648,6 +651,7 @@
// same referentiel in both db
Assert.assertNotNull(result);
+ Assert.assertNull(result.getError());
DatabaseSynchroFixtures fixturesExternal;
DatabaseSynchroFixtures fixturesInternal;
@@ -686,6 +690,8 @@
result = helper.synchronize(externalConnectionProperties,
localConnectionProperties,
dialect);
+ Assert.assertNotNull(result);
+ Assert.assertNull(result.getError());
fixturesExternal = new DatabaseSynchroFixtures(
helper, internalDb, externalConnection);
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java 2013-02-13 21:48:46 UTC (rev 410)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -25,33 +25,30 @@
*/
import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import fr.ifremer.tutti.persistence.service.TuttiPersistenceServiceLocator;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import org.hibernate.dialect.Dialect;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
-import org.junit.Ignore;
import org.junit.Rule;
+import org.junit.Test;
import org.junit.rules.TestName;
import org.springframework.jdbc.support.JdbcUtils;
-import java.io.IOException;
import java.sql.Connection;
+import java.sql.PreparedStatement;
import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.util.Properties;
/**
* @author tchemit <chemit(a)codelutin.com>
* @since 1.0
*/
-@Ignore
public class ReferentialSynchronizeServiceImplTest {
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(ReferentialSynchronizeServiceImplTest.class);
-
@ClassRule
public static final DatabaseResource dbResource = DatabaseResource.writeDb();
@@ -60,25 +57,136 @@
protected ReferentialSynchronizeService service;
- protected Connection externalConnection;
+ protected Properties remoteConnectionProperties;
- protected Connection internalConnection;
+ protected Properties localConnectionProperties;
+ protected Connection remoteConnection;
+
+ protected Connection localConnection;
+
+ private Dialect dialect;
+
+ protected ReferentialSynchronizeHelper helper;
+
@Before
public void setUp() throws Exception {
+
+ // create read-only remote db
+ remoteConnectionProperties = new Properties();
+ dbResource.copyDb(n.getMethodName(), false, remoteConnectionProperties);
+
+ // create services
+ helper = new ReferentialSynchronizeHelper();
service = TuttiPersistenceServiceLocator.getReferentialSynchronizeService();
+
+ // create grab local stuff
+ localConnectionProperties = service.getLocalConnectionProperties();
+ dialect = service.getLocalDialect();
+
+ // open connections
+ remoteConnection = TuttiEntities.createConnection(remoteConnectionProperties);
+ localConnection = TuttiEntities.createConnection(localConnectionProperties);
}
@After
public void tearDown() throws Exception {
service = null;
- JdbcUtils.closeConnection(internalConnection);
- JdbcUtils.closeConnection(externalConnection);
+ remoteConnectionProperties = null;
+ dialect = null;
+ helper = null;
+ JdbcUtils.closeConnection(localConnection);
+ JdbcUtils.closeConnection(remoteConnection);
}
- protected void createExternalDb() throws IOException, SQLException {
- externalConnection = dbResource.createEmptyDb(n.getMethodName(), "newDb");
- Assert.assertNotNull(externalConnection);
+ @Test
+ public void synchronize() throws SQLException {
+
+ TuttiDatabaseMetadata remoteSchema =
+ helper.loadDatabaseMetadata(remoteConnection, dialect);
+
+ DatabaseSynchroFixtures fixturesRemote;
+ DatabaseSynchroFixtures fixturesLocal;
+ ReferentialSynchronizeResult result;
+
+ // add some stuff on remote db
+
+ // add a new status
+ remoteConnection.prepareStatement("INSERT INTO STATUS(CODE, NAME) VALUES (4, 'NEW')").executeUpdate();
+
+ // add a new aggregation_level
+ remoteConnection.prepareStatement("INSERT INTO AGGREGATION_LEVEL (ID, NAME, RANK_ORDER, UPDATE_DATE) VALUES (-1000, 'NAME', -1000, NULL)").executeUpdate();
+
+ // update a unit
+ PreparedStatement preparedStatement = remoteConnection.prepareStatement("UPDATE UNIT SET SYMBOL = 'Auncun un?', UPDATE_DATE=? WHERE ID=1");
+ preparedStatement.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
+ preparedStatement.executeUpdate();
+
+ remoteConnection.commit();
+
+ fixturesRemote = new DatabaseSynchroFixtures(
+ helper, remoteSchema, remoteConnection);
+
+ result = service.synchronize(remoteConnectionProperties);
+
+ // same referentiel in both db
+ Assert.assertNotNull(result);
+ Assert.assertNull(result.getError());
+
+ fixturesLocal = new DatabaseSynchroFixtures(
+ helper, remoteSchema, localConnection);
+
+ // on entities, only updates in table is with no update_date
+ for (TuttiTable tuttiTable : TuttiTable.getEntityTables()) {
+ String tableName = tuttiTable.name();
+ int nbInserts = result.getNbInserts(tableName);
+ int nbUpdates = result.getNbUpdates(tableName);
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int expectedRows = result.getNbRows(tableName);
+ int expectedInserts = 0;
+ int expectedUpdates = 0;
+ TuttiTableMetadata table = remoteSchema.getTable(tableName);
+ if (!table.isWithUpdateDateColumn()) {
+ // updates everything
+ expectedUpdates = nbRemote;
+ }
+
+ switch (tuttiTable) {
+ case STATUS:
+ expectedInserts = 1;
+ expectedUpdates--;
+ break;
+ case UNIT:
+
+ expectedUpdates = 1;
+ break;
+
+ case AGGREGATION_LEVEL:
+ expectedInserts = 1;
+ break;
+ }
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s inserts, but was only %s", tableName, expectedInserts, nbInserts), expectedInserts, nbInserts, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, expectedUpdates, nbUpdates), expectedUpdates, nbUpdates, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows treated, but was only %s", tableName, expectedRows, nbInserts + nbUpdates), expectedRows, nbInserts + nbUpdates, 0);
+ }
+
+ // on associations, only inserts
+ for (TuttiTable tuttiTable : TuttiTable.getAssociationTables()) {
+ String tableName = tuttiTable.name();
+ int nbInserts = result.getNbInserts(tableName);
+ int nbUpdates = result.getNbUpdates(tableName);
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int expectedRows = result.getNbRows(tableName);
+ int expectedInserts = nbRemote;
+ int expectedUpdates = 0;
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s inserts, but was only %s", tableName, expectedInserts, nbInserts), expectedInserts, nbInserts, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, expectedUpdates, nbUpdates), expectedUpdates, nbUpdates, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows treated, but was only %s", tableName, expectedRows, nbInserts + nbUpdates), expectedRows, nbInserts + nbUpdates, 0);
+ }
+
}
-
}
Copied: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java (from rev 410, trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java)
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java (rev 0)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java 2013-02-14 08:42:09 UTC (rev 411)
@@ -0,0 +1,160 @@
+package fr.ifremer.tutti.persistence.service.synchro;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.TuttiEntities;
+import fr.ifremer.tutti.persistence.service.TuttiPersistenceServiceLocator;
+import org.hibernate.dialect.Dialect;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+import org.springframework.jdbc.support.JdbcUtils;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Properties;
+
+/**
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class ReferentialSynchronizeServiceImplUpTodateTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.writeDb();
+
+ @Rule
+ public final TestName n = new TestName();
+
+ protected ReferentialSynchronizeService service;
+
+ protected Properties remoteConnectionProperties;
+
+ protected Properties localConnectionProperties;
+
+ protected Connection remoteConnection;
+
+ protected Connection localConnection;
+
+ private Dialect dialect;
+
+ protected ReferentialSynchronizeHelper helper;
+
+ @Before
+ public void setUp() throws Exception {
+
+ // create read-only remote db
+ remoteConnectionProperties = new Properties();
+ dbResource.copyDb(n.getMethodName(), false, remoteConnectionProperties);
+
+ // create services
+ helper = new ReferentialSynchronizeHelper();
+ service = TuttiPersistenceServiceLocator.getReferentialSynchronizeService();
+
+ // create grab local stuff
+ localConnectionProperties = service.getLocalConnectionProperties();
+ dialect = service.getLocalDialect();
+
+ // open connections
+ remoteConnection = TuttiEntities.createConnection(remoteConnectionProperties);
+ localConnection = TuttiEntities.createConnection(localConnectionProperties);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ service = null;
+ remoteConnectionProperties = null;
+ dialect = null;
+ helper = null;
+ JdbcUtils.closeConnection(localConnection);
+ JdbcUtils.closeConnection(remoteConnection);
+ }
+
+ @Test
+ public void synchronize() throws SQLException {
+
+ TuttiDatabaseMetadata remoteSchema =
+ helper.loadDatabaseMetadata(remoteConnection, dialect);
+
+ DatabaseSynchroFixtures fixturesRemote;
+ DatabaseSynchroFixtures fixturesLocal;
+ ReferentialSynchronizeResult result;
+
+ fixturesRemote = new DatabaseSynchroFixtures(
+ helper, remoteSchema, remoteConnection);
+
+ result = service.synchronize(remoteConnectionProperties);
+
+ // same referentiel in both db
+ Assert.assertNotNull(result);
+ Assert.assertNull(result.getError());
+
+ fixturesLocal = new DatabaseSynchroFixtures(
+ helper, remoteSchema, localConnection);
+
+ // on entities, only updates in table is with no update_date
+ for (TuttiTable tuttiTable : TuttiTable.getEntityTables()) {
+ String tableName = tuttiTable.name();
+ int nbInserts = result.getNbInserts(tableName);
+ int nbUpdates = result.getNbUpdates(tableName);
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int expectedRows = result.getNbRows(tableName);
+ int expectedInserts = 0;
+ int expectedUpdates = 0;
+ TuttiTableMetadata table = remoteSchema.getTable(tableName);
+ if (!table.isWithUpdateDateColumn()) {
+ // updates everything
+ expectedUpdates = nbRemote;
+ }
+
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s inserts, but was only %s", tableName, expectedInserts, nbInserts), expectedInserts, nbInserts, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, expectedUpdates, nbUpdates), expectedUpdates, nbUpdates, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows treated, but was only %s", tableName, expectedRows, nbInserts + nbUpdates), expectedRows, nbInserts + nbUpdates, 0);
+ }
+
+ // on associations, only inserts
+ for (TuttiTable tuttiTable : TuttiTable.getAssociationTables()) {
+ String tableName = tuttiTable.name();
+ int nbInserts = result.getNbInserts(tableName);
+ int nbUpdates = result.getNbUpdates(tableName);
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int expectedRows = result.getNbRows(tableName);
+ int expectedInserts = nbRemote;
+ int expectedUpdates = 0;
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s inserts, but was only %s", tableName, expectedInserts, nbInserts), expectedInserts, nbInserts, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, expectedUpdates, nbUpdates), expectedUpdates, nbUpdates, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows treated, but was only %s", tableName, expectedRows, nbInserts + nbUpdates), expectedRows, nbInserts + nbUpdates, 0);
+ }
+ }
+}
1
0
r410 - in trunk/tutti-persistence/src: main/java/fr/ifremer/tutti/persistence main/java/fr/ifremer/tutti/persistence/entities main/java/fr/ifremer/tutti/persistence/service main/java/fr/ifremer/tutti/persistence/service/synchro main/resources test/java/fr/ifremer/tutti/persistence test/java/fr/ifremer/tutti/persistence/service/synchro
by tchemit@users.forge.codelutin.com 13 Feb '13
by tchemit@users.forge.codelutin.com 13 Feb '13
13 Feb '13
Author: tchemit
Date: 2013-02-13 22:48:46 +0100 (Wed, 13 Feb 2013)
New Revision: 410
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/410
Log:
refs #1874: [IMP/EXP] - Synchronisation de r?\195?\169f?\195?\169rentiel
Added:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiEntityTableMetadata.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/DatabaseSynchroFixtures.java
Removed:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java
Modified:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistence.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiDatabaseMetadata.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTable.java
trunk/tutti-persistence/src/main/resources/tuttiBeanRefFactory.xml
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseFixtures.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistence.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistence.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistence.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -329,12 +329,17 @@
//-- Species Batch methods --//
//------------------------------------------------------------------------//
+ /**
+ * Get all root {@link SpeciesBatch} for the given fishing operation.
+ * <p/>
+ * <strong>Note:</strong> All childs of the batch should be loaded here.
+ *
+ * @param fishingOperationId if of the fishing operation to seek
+ * @return the list of root {@link SpeciesBatch}
+ * @since 1.0
+ */
List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId);
-// List<SpeciesBatch> getAllSpeciesBatch(String fishingOperationId);
-//
-// SpeciesBatch getSpeciesBatch(String id);
-
@Transactional(readOnly = false)
SpeciesBatch createSpeciesBatch(SpeciesBatch bean, String parentBatchId);
@@ -350,9 +355,26 @@
@Transactional(readOnly = false)
void changeSpeciesBatchSpecies(String batchId, Species species);
- List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
- String speciesBatchId);
+ /**
+ * Get all frequencies for the given species batch.
+ *
+ * @param speciesBatchId the id of the species batch to seek.
+ * @return the list of frequencies for the given specues batch id
+ * @since 1.0
+ */
+ List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(String speciesBatchId);
+ /**
+ * Save all given {@link SpeciesBatchFrequency} into the given
+ * {@code speciesBatchId}. If some are not existing then creates them.
+ * <p/>
+ * <strong>Note:</strong> This will as a side effect remove all previous frequency for this species batch.
+ *
+ * @param speciesBatchId id of the {@link SpeciesBatch} to use
+ * @param frequencies list of frequencies to create or update
+ * @return the persisted list of frequencies
+ * @since 1.0
+ */
@Transactional(readOnly = false)
List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(String speciesBatchId,
List<SpeciesBatchFrequency> frequencies);
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -30,6 +30,8 @@
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import fr.ifremer.tutti.persistence.entities.data.FishingOperationAware;
import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
@@ -92,6 +94,10 @@
return Maps.uniqueIndex(list, GET_TAXON_ID);
}
+ public static Multimap<String, Species> splitByReferenceTaxonId(Iterable<Species> list) {
+ return Multimaps.index(list, GET_TAXON_ID);
+ }
+
public static final Function<Species, String> GET_TAXON_ID = new Function<Species, String>() {
@Override
public String apply(Species input) {
@@ -184,7 +190,6 @@
}
}
-
public static Connection createConnection(Properties connectionProperties) throws SQLException {
return createConnection(
connectionProperties.getProperty(Environment.URL),
@@ -212,6 +217,12 @@
return result;
}
+ public static void fillConnectionProperties(Properties p, String url, String username, String password) {
+ p.put(Environment.URL, url);
+ p.put(Environment.USER, username);
+ p.put(Environment.PASS, password);
+ }
+
protected static class IdPredicate<B extends IdAware> implements Predicate<B> {
private final String id;
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceService.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceService.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -41,8 +41,24 @@
@Transactional(readOnly = true)
public interface SpeciesBatchPersistenceService extends TuttiPersistenceServiceImplementor {
+ /**
+ * Get all root {@link SpeciesBatch} for the given fishing operation.
+ * <p/>
+ * <strong>Note:</strong> All childs of the batch should be loaded here.
+ *
+ * @param fishingOperationId if of the fishing operation to seek
+ * @return the list of root {@link SpeciesBatch}
+ * @since 1.0
+ */
List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId);
+ /**
+ * Get all frequencies for the given species batch.
+ *
+ * @param speciesBatchId the id of the species batch to seek.
+ * @return the list of frequencies for the given specues batch id
+ * @since 1.0
+ */
List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
String speciesBatchId);
@@ -68,6 +84,17 @@
@Transactional(readOnly = false)
void changeSpeciesBatchSpecies(String batchId, Species species);
+ /**
+ * Save all given {@link SpeciesBatchFrequency} into the given
+ * {@code speciesBatchId}. If some are not existing then creates them.
+ * <p/>
+ * <strong>Note:</strong> This will as a side effect remove all previous frequency for this species batch.
+ *
+ * @param speciesBatchId id of the {@link SpeciesBatch} to use
+ * @param frequencies list of frequencies to create or update
+ * @return the persisted list of frequencies
+ * @since 1.0
+ */
@Transactional(readOnly = false)
List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(String speciesBatchId,
List<SpeciesBatchFrequency> frequencies);
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -24,6 +24,8 @@
* #L%
*/
+import com.google.common.base.Predicate;
+import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import org.apache.commons.logging.Log;
@@ -39,6 +41,7 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
+import java.util.List;
import java.util.Properties;
import java.util.Set;
@@ -55,6 +58,20 @@
private static final Log log =
LogFactory.getLog(ReferentialSynchronizeHelper.class);
+ public static final Predicate<TuttiTableMetadata> IS_ENTITY_TABLE = new Predicate<TuttiTableMetadata>() {
+ @Override
+ public boolean apply(TuttiTableMetadata input) {
+ return input instanceof TuttiEntityTableMetadata;
+ }
+ };
+
+ public static final Predicate<TuttiTableMetadata> IS_ASSOCIATION_TABLE = new Predicate<TuttiTableMetadata>() {
+ @Override
+ public boolean apply(TuttiTableMetadata input) {
+ return input instanceof TuttiAssociationTableMetadata;
+ }
+ };
+
/**
* Synchronize database given from {@code localProperties} (means the
* database to update) with remote database (means the database which
@@ -87,10 +104,11 @@
// create remote Connection
synchConnection = TuttiEntities.createConnection(remoteProperties);
-
// load metas
- TuttiDatabaseMetadata targetMeta = loadDatabaseMetadata(targetConnection, dialect);
- TuttiDatabaseMetadata synchMeta = loadDatabaseMetadata(synchConnection, dialect);
+ TuttiDatabaseMetadata targetMeta =
+ loadDatabaseMetadata(targetConnection, dialect);
+ TuttiDatabaseMetadata synchMeta =
+ loadDatabaseMetadata(synchConnection, dialect);
// check schema
try {
@@ -108,8 +126,14 @@
for (TuttiTable tuttiTable : TuttiTable.values()) {
- synchronizeTable(tuttiTable,
- synchMeta,
+ String tableName = tuttiTable.name();
+
+ TuttiTableMetadata table = synchMeta.getTable(tableName);
+
+ if (log.isInfoEnabled()) {
+ log.info("Synchronize table: " + tableName);
+ }
+ synchronizeTable(table,
targetConnection,
synchConnection,
result);
@@ -122,7 +146,9 @@
}
} catch (SQLException e) {
try {
- targetConnection.rollback();
+ if (targetConnection != null) {
+ targetConnection.rollback();
+ }
} catch (SQLException e1) {
// ignore the rolback error
@@ -195,7 +221,7 @@
/**
* Gets the last updateDate for the given {@code table} using
- * the given datasource
+ * the given datasource.
*
* @param connection connection to data source to query
* @param table the table to query
@@ -209,7 +235,7 @@
if (table.isWithUpdateDateColumn()) {
- String sql = table.getGetMaxUpdateDateQuery();
+ String sql = table.getMaxUpdateDateQuery();
PreparedStatement statement = connection.prepareStatement(sql);
try {
@@ -229,29 +255,40 @@
TuttiTableMetadata table,
Date fromDate) throws SQLException {
- String sql = table.getGetDataToUpdateQuery();
+ String sql = fromDate == null ?
+ table.getDataToUpdateQueryWithNull() :
+ table.getDataToUpdateQuery();
PreparedStatement statement = connection.prepareStatement(sql);
- if (table.isWithUpdateDateColumn()) {
+ if (table.useUpdateDateColumn() &&
+ table.isWithUpdateDateColumn() &&
+ fromDate != null) {
statement.setDate(1, new java.sql.Date(fromDate.getTime()));
}
+ statement.setFetchSize(1000);
ResultSet result = statement.executeQuery();
return result;
}
- public Set<String> getExistingIds(Connection connection,
- TuttiTableMetadata table) throws SQLException {
+ public Set<List<String>> getExistingPrimaryKeys(Connection connection,
+ TuttiTableMetadata table) throws SQLException {
- String sql = table.getGetExistingIdsQuery();
+ Set<String> pkNames = table.getPkNames();
+ int pkCount = pkNames.size();
+ String sql = table.getExistingPrimaryKeysQuery();
PreparedStatement statement = connection.prepareStatement(sql);
- Set<String> result = Sets.newHashSet();
+ Set<List<String>> result = Sets.newHashSet();
try {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
- result.add(String.valueOf(resultSet.getObject(1)));
+ List<String> pk = Lists.newArrayListWithCapacity(pkCount);
+ for (int i = 1; i <= pkCount; i++) {
+ pk.add(String.valueOf(resultSet.getObject(i)));
+ }
+ result.add(pk);
}
statement.close();
return result;
@@ -260,18 +297,44 @@
}
}
+ public long countTable(Connection connection,
+ TuttiTableMetadata table) throws SQLException {
+
+ String sql = table.getCountQuery();
+
+ PreparedStatement statement = connection.prepareStatement(sql);
+
+ try {
+ ResultSet resultSet = statement.executeQuery();
+ resultSet.next();
+ long result = resultSet.getLong(1);
+ statement.close();
+ return result;
+ } finally {
+ TuttiEntities.closeSilently(statement);
+ }
+ }
+
+ protected List<String> getPk(ResultSet incomingData, int[] pkIndexs) throws SQLException {
+ List<String> result = Lists.newArrayListWithCapacity(pkIndexs.length);
+ for (int pkIndex : pkIndexs) {
+ Object pk = incomingData.getObject(pkIndex);
+ result.add(pk == null ? null : String.valueOf(pk));
+ }
+ return result;
+ }
+
public void updateTable(Connection connection,
TuttiTableMetadata table,
- Set<String> existingIds,
+ Set<List<String>> existingIds,
ResultSet incomingData,
ReferentialSynchronizeResult result) throws SQLException {
int columnCount = table.getColumnsCount();
-
String tableName = table.getName();
- int pkIndex = table.getPkIndex();
+ int[] pkIndex = table.getPkIndexs();
String insertSql = table.getInsertQuery();
String updateSql = table.getUpdateQuery();
@@ -281,28 +344,29 @@
result.addTableName(tableName);
+ int countR = 0;
+ int insertCount = 0;
+ int updateCount = 0;
do {
- Object pk = incomingData.getObject(pkIndex);
+ List<String> pk = getPk(incomingData, pkIndex);
- String pkAsString = String.valueOf(pk);
PreparedStatement statement;
String sql;
- boolean doUpdate = existingIds.contains(pkAsString);
+ boolean doUpdate = existingIds.contains(pk);
if (doUpdate) {
// use update query
statement = updateStatement;
sql = updateSql;
-
- result.addUpdate(tableName, pkAsString);
+ updateCount++;
} else {
// use insert query
sql = insertSql;
statement = insertStatement;
- result.addInsert(tableName, pkAsString);
+ insertCount++;
}
for (int c = 1; c <= columnCount; c++) {
@@ -310,47 +374,108 @@
}
if (doUpdate) {
- statement.setObject(columnCount + 1, pk);
+
+ // add pk at end parameters
+
+ int columnCountIndex = columnCount + 1;
+
+ for (String pkColumn : pk) {
+ statement.setObject(columnCountIndex++, pkColumn);
+ }
}
if (log.isDebugEnabled()) {
+ String pkAsString = pk.toString();
log.debug(String.format("[%s] Execute query %s (pk:%s)", tableName, sql, pkAsString));
}
+ statement.addBatch();
- statement.executeUpdate();
+ countR++;
+
+ if (insertCount > 0 && insertCount % 1000 == 0) {
+ insertStatement.executeBatch();
+ insertStatement.clearBatch();
+ }
+ if (updateCount > 0 && updateCount % 1000 == 0) {
+ updateStatement.executeBatch();
+ updateStatement.clearBatch();
+
+ }
+ if (countR % 10000 == 0) {
+ if (log.isInfoEnabled()) {
+ log.info("Rows Done: " + countR);
+ }
+ }
}
while (incomingData.next());
+ result.addInserts(tableName, insertCount);
+ result.addUpdates(tableName, updateCount);
+ if (log.isInfoEnabled()) {
+ log.info("Rows Done: " + countR);
+ }
+
+ if (insertCount > 0 && insertCount % 1000 != 0) {
+ insertStatement.executeBatch();
+ }
+ if (updateCount > 0 && updateCount % 1000 != 0) {
+ updateStatement.executeBatch();
+
+ }
if (log.isDebugEnabled()) {
log.debug(String.format("[%s] INSERT count: %s", tableName, result.getNbInserts(tableName)));
log.debug(String.format("[%s] UPDATE count: %s", tableName, result.getNbUpdates(tableName)));
}
}
- public void synchronizeTable(TuttiTable tuttiTable,
- TuttiDatabaseMetadata dbMeta,
+ public void synchronizeTable(TuttiTableMetadata table,
Connection localConnection,
Connection remoteConnection,
ReferentialSynchronizeResult result) throws SQLException {
- TuttiTableMetadata table = dbMeta.getTable(tuttiTable.name());
+ // get last updateDate used by local db
+ Date updateDate = getLastUpdateDate(localConnection, table);
- Date updateDate = getLastUpdateDate(remoteConnection, table);
+ if (log.isInfoEnabled()) {
+ log.info("[" + table.getName() + "] updateDate: " + updateDate);
+ }
// get data to synch
ResultSet dataToUpdate = getDataToUpdate(remoteConnection,
table,
updateDate);
+ if (log.isInfoEnabled()) {
+ log.info("[" + table.getName() + "] dataToUpdate: " + dataToUpdate);
+ }
try {
if (dataToUpdate.next()) {
// there is some data to update
+ String tableName = table.getName();
+
+
+ TuttiTable tuttiTable = TuttiTable.valueOf(tableName);
+ if (tuttiTable.isAssociation()) {
+ PreparedStatement deleteStatement =
+ localConnection.prepareStatement(
+ "DELETE FROM " + tableName);
+ deleteStatement.execute();
+ if (log.isInfoEnabled()) {
+ log.info("Delete from association: " + tableName);
+ }
+ }
+
// gets existing ids in the target db
- Set<String> existingIds = getExistingIds(localConnection,
- table);
+ Set<List<String>> existingIds = getExistingPrimaryKeys(localConnection, table);
+
+ if (log.isInfoEnabled()) {
+ log.info("[" + table.getName() + "] existingIds: " + existingIds.size());
+ }
+
+ // update table content
updateTable(localConnection,
table,
existingIds,
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -24,12 +24,11 @@
* #L%
*/
-import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Multimap;
+import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-import java.util.Collection;
+import java.util.Map;
import java.util.Set;
/**
@@ -42,9 +41,9 @@
protected Exception error;
- protected final Multimap<String, String> inserts = HashMultimap.create();
+ protected final Map<String, Integer> insertHits = Maps.newTreeMap();
- protected final Multimap<String, String> updates = HashMultimap.create();
+ protected final Map<String, Integer> updateHits = Maps.newTreeMap();
protected final Set<String> tableNames = Sets.newHashSet();
@@ -73,28 +72,28 @@
return ImmutableSet.copyOf(tableNames);
}
- public Collection<String> getInserts(String tableName) {
- return inserts.get(tableName);
- }
-
- public Collection<String> getUpdates(String tableName) {
- return updates.get(tableName);
- }
-
public int getNbInserts(String tableName) {
- return getInserts(tableName).size();
+ Integer result = insertHits.get(tableName);
+ if (result == null) {
+ result = 0;
+ }
+ return result;
}
public int getNbUpdates(String tableName) {
- return getUpdates(tableName).size();
+ Integer result = updateHits.get(tableName);
+ if (result == null) {
+ result = 0;
+ }
+ return result;
}
- public void addUpdate(String tableName, String pkAsString) {
- updates.put(tableName, pkAsString);
+ public void addUpdates(String tableName, int nb) {
+ updateHits.put(tableName, getNbUpdates(tableName) + nb);
}
- public void addInsert(String tableName, String pkAsString) {
- inserts.put(tableName, pkAsString);
+ public void addInserts(String tableName, int nb) {
+ insertHits.put(tableName, getNbInserts(tableName) + nb);
}
public void addTableName(String tableName) {
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -24,9 +24,9 @@
* #L%
*/
+import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import fr.ifremer.tutti.persistence.service.AbstractPersistenceService;
import org.apache.commons.dbcp.BasicDataSource;
-import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionFactoryImplementor;
import org.springframework.beans.factory.annotation.Autowired;
@@ -58,9 +58,10 @@
public Properties getLocalConnectionProperties() {
if (dbconnexionProperties == null) {
dbconnexionProperties = new Properties();
- dbconnexionProperties.put(Environment.URL, dataSource.getUrl());
- dbconnexionProperties.put(Environment.USER, dataSource.getUsername());
- dbconnexionProperties.put(Environment.PASS, dataSource.getPassword());
+ TuttiEntities.fillConnectionProperties(dbconnexionProperties,
+ dataSource.getUrl(),
+ dataSource.getUsername(),
+ dataSource.getPassword());
}
return dbconnexionProperties;
}
@@ -75,6 +76,7 @@
@Override
public ReferentialSynchronizeResult synchronize(Properties remoteConnectionProperties) {
+ //TODO Evict all caches, restart application (but not from here,...)
return helper.synchronize(getLocalConnectionProperties(),
remoteConnectionProperties,
getLocalDialect());
Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -0,0 +1,75 @@
+package fr.ifremer.tutti.persistence.service.synchro;
+
+/*
+ * #%L
+ * Tutti :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import com.google.common.base.Preconditions;
+import org.apache.commons.collections.CollectionUtils;
+import org.hibernate.tool.hbm2ddl.TableMetadata;
+
+import java.sql.DatabaseMetaData;
+
+/**
+ * Specialized of {@link TuttiEntityTableMetadata} for association table.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class TuttiAssociationTableMetadata extends TuttiTableMetadata {
+
+ private final String dataToUpdateQuery;
+
+ public TuttiAssociationTableMetadata(TableMetadata delegate,
+ DatabaseMetaData meta) {
+ super(delegate, meta);
+ Preconditions.checkState(CollectionUtils.isNotEmpty(getPkNames()));
+ Preconditions.checkState(getPkNames().size() > 1);
+
+ StringBuilder queryParams = new StringBuilder("");
+ for (String columnName : getColumnNames()) {
+ queryParams.append(", ").append(columnName);
+ }
+ StringBuilder query = new StringBuilder("SELECT ");
+ query.append(queryParams.substring(2));
+ query.append(" FROM ").append(getName());
+
+ dataToUpdateQuery = query.toString();
+ }
+
+ @Override
+ public String getDataToUpdateQuery() {
+ return dataToUpdateQuery;
+ }
+
+ @Override
+ public String getDataToUpdateQueryWithNull() {
+ return dataToUpdateQuery;
+ }
+
+ @Override
+ public boolean useUpdateDateColumn() {
+ return false;
+ }
+
+}
Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiAssociationTableMetadata.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiDatabaseMetadata.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiDatabaseMetadata.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiDatabaseMetadata.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -71,6 +71,18 @@
return getTable(name, "PUBLIC", null, false);
}
+ public TuttiEntityTableMetadata getEntityTable(String name) throws HibernateException {
+ TuttiTableMetadata table = getTable(name);
+ Preconditions.checkState(ReferentialSynchronizeHelper.IS_ENTITY_TABLE.apply(table));
+ return (TuttiEntityTableMetadata) table;
+ }
+
+ public TuttiAssociationTableMetadata getAssociationTable(String name) throws HibernateException {
+ TuttiTableMetadata table = getTable(name);
+ Preconditions.checkState(ReferentialSynchronizeHelper.IS_ASSOCIATION_TABLE.apply(table));
+ return (TuttiAssociationTableMetadata) table;
+ }
+
public int getTableCount() {
return tables.size();
}
@@ -95,7 +107,14 @@
name, schema, catalog, isQuoted);
Preconditions.checkNotNull(tableMetadata,
"Could not find db table " + name);
- tuttiTableMetadata = new TuttiTableMetadata(tableMetadata, meta);
+ TuttiTable tuttiTable = TuttiTable.valueOf(name);
+ Preconditions.checkNotNull(tuttiTable,
+ "Could not find db table " + tuttiTable);
+ if (tuttiTable.isAssociation()) {
+ tuttiTableMetadata = new TuttiAssociationTableMetadata(tableMetadata, meta);
+ } else {
+ tuttiTableMetadata = new TuttiEntityTableMetadata(tableMetadata, meta);
+ }
Preconditions.checkNotNull(tuttiTableMetadata,
"Could not find db table " + name);
tables.put(key, tuttiTableMetadata);
Copied: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiEntityTableMetadata.java (from rev 400, trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java)
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiEntityTableMetadata.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiEntityTableMetadata.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -0,0 +1,85 @@
+package fr.ifremer.tutti.persistence.service.synchro;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import com.google.common.base.Preconditions;
+import org.apache.commons.collections.CollectionUtils;
+import org.hibernate.tool.hbm2ddl.TableMetadata;
+
+import java.sql.DatabaseMetaData;
+
+/**
+ * Default implementation of the {@link TuttiTableMetadata} for a
+ * {@code entity} table, says with a simple primary key.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class TuttiEntityTableMetadata extends TuttiTableMetadata {
+
+ private final String dataToUpdateQuery;
+ private final String dataToUpdateQueryWithNull;
+
+ public TuttiEntityTableMetadata(TableMetadata delegate,
+ DatabaseMetaData meta) {
+ super(delegate, meta);
+
+ Preconditions.checkState(CollectionUtils.isNotEmpty(getPkNames()));
+ Preconditions.checkState(getPkNames().size() == 1);
+
+ StringBuilder queryParams = new StringBuilder("");
+ for (String columnName : getColumnNames()) {
+ queryParams.append(", ").append(columnName);
+ }
+ StringBuilder query = new StringBuilder("SELECT ");
+ query.append(queryParams.substring(2));
+ query.append(" FROM ").append(getName());
+
+ dataToUpdateQueryWithNull= query.toString();
+
+ if (isWithUpdateDateColumn()) {
+
+ // add a filter
+ query.append(" WHERE (update_date IS NULL OR update_date > ?)");
+ }
+ dataToUpdateQuery = query.toString();
+ }
+
+ @Override
+ public String getDataToUpdateQuery() {
+ return dataToUpdateQuery;
+ }
+
+ @Override
+ public String getDataToUpdateQueryWithNull() {
+ return dataToUpdateQueryWithNull;
+ }
+
+ @Override
+ public boolean useUpdateDateColumn() {
+ return true;
+ }
+
+}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTable.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTable.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTable.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -24,6 +24,10 @@
* #L%
*/
+import com.google.common.collect.Lists;
+
+import java.util.List;
+
/**
* TODO
*
@@ -42,32 +46,32 @@
PARAMETER,
MATRIX,
FRACTION,
- //assocation:FRACTION2MATRIX,
+ FRACTION2MATRIX(true),
METHOD,
PMFM,
- //assocation:PMFM2QUALITATIVE_VALUE,
+ PMFM2QUALITATIVE_VALUE(true),
// GEAR
GEAR_CLASSIFICATION,
- //assocation:GEAR_CLASSIFICATION_ASSOCIATIO,
+ GEAR_CLASSIFICATION_ASSOCIATIO(true),
GEAR,
- //assocation:GEAR_ASSOCIATION,
+ GEAR_ASSOCIATION(true),
// LOCATION
LOCATION_CLASSIFICATION,
LOCATION_LEVEL,
- //assocation:LOCATION_ASSOCIATION,
+ LOCATION_ASSOCIATION(true),
LOCATION,
- //assocation:LOCATION_HIERARCHY,
- LOCATION_HIERARCHY_EXCEPTION,
+ LOCATION_HIERARCHY(true),
+ LOCATION_HIERARCHY_EXCEPTION(true),
// TAXON
TAXONOMIC_LEVEL,
REFERENCE_TAXON,
TAXON_NAME,
- //assocation:TAXON_INFORMATION,
- TAXON_INFORMATION_HISTORY,
- //assocation:VIRTUAL_COMPONENT,
+ TAXON_INFORMATION(true),
+ TAXON_INFORMATION_HISTORY(true),
+ VIRTUAL_COMPONENT(true),
TAXON_NAME_HISTORY,
REFERENCE_DOCUMENT,
AUTHOR,
@@ -77,34 +81,68 @@
TAXON_GROUP_TYPE,
TAXON_GROUP,
TAXON_GROUP_HISTORICAL_RECORD,
- //assocation:TAXON_GROUP_INFORMATION,
+ TAXON_GROUP_INFORMATION(true),
// CONVERSION
ROUND_WEIGHT_CONVERSION,
WEIGHT_LENGTH_CONVERSION,
- UNIT_CONVERSION,
+ UNIT_CONVERSION(true),
// VESSEL
VESSEL_TYPE,
- //assocation:VESSEL_REGISTRATION_PERIOD,
- VESEL_FEATURES,
+ VESSEL_REGISTRATION_PERIOD(true),
+ VESSEL_FEATURES,
VESSEL,
// PERSON
USER_PROFIL,
DEPARTMENT,
PERSON,
- //assocation:PERSON2USER_PROFIL,
-
+ PERSON2USER_PROFIL(true),
+
//ORDER
ORDER_ITEM,
- ORDER_ITEM_TYPE,
//OTHER
PRECISION_TYPE,
- NUMERICAL_PECISION,
+ NUMERICAL_PRECISION,
PHOTO_TYPE,
OBJECT_TYPE,
ORDER_TYPE,
- ANALYSIS_INSTRUMENT
+ ANALYSIS_INSTRUMENT;
+
+
+ private final boolean association;
+
+ private TuttiTable() {
+ this(false);
+ }
+
+ private TuttiTable(boolean association) {
+ this.association = association;
+ }
+
+ public boolean isAssociation() {
+ return association;
+ }
+
+ public static TuttiTable[] getEntityTables() {
+ List<TuttiTable> result = Lists.newArrayList();
+ for (TuttiTable table : values()) {
+ if (!table.isAssociation()) {
+ result.add(table);
+ }
+ }
+ return result.toArray(new TuttiTable[result.size()]);
+ }
+
+ public static TuttiTable[] getAssociationTables() {
+ List<TuttiTable> result = Lists.newArrayList();
+ for (TuttiTable table : values()) {
+ if (table.isAssociation()) {
+ result.add(table);
+ }
+ }
+ return result.toArray(new TuttiTable[result.size()]);
+ }
}
Deleted: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -1,298 +0,0 @@
-package fr.ifremer.tutti.persistence.service.synchro;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * 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%
- */
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Sets;
-import fr.ifremer.tutti.persistence.entities.TuttiEntities;
-import org.apache.commons.collections.CollectionUtils;
-import org.hibernate.mapping.ForeignKey;
-import org.hibernate.tool.hbm2ddl.ColumnMetadata;
-import org.hibernate.tool.hbm2ddl.ForeignKeyMetadata;
-import org.hibernate.tool.hbm2ddl.IndexMetadata;
-import org.hibernate.tool.hbm2ddl.TableMetadata;
-
-import java.lang.reflect.Field;
-import java.sql.DatabaseMetaData;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-
-/**
- * Overrides of the {@link TableMetadata} with some improvements:
- * <ul>
- * <li>Obtains number of columns via {@link #getColumnsCount()}</li>
- * <li>Obtains all columns names available via {@link #getColumnNames()}</li>
- * <li>Obtains primary key column names via {@link #getPkNames()}</li>
- * <li>Is table a association table via {@link #isAssociationTable()}</li>
- * </ul>
- * <p/>
- * And others methods used to synchronize referentials:
- * <p/>
- * <ul>
- * <li>Obtains query to get all existing ids: {@link #getGetExistingIdsQuery()}</li>
- * <li>Obtains query to update a row of the table (column names order is the one introduced by method {@link #getColumnNames()}: {@link #getUpdateQuery()}</li>
- * <li>Obtains query to insert a row in the table (column names order is the one introduced by method {@link #getColumnNames()}: {@link #getInsertQuery()}</li>
- * <li>Obtains query to get max update date (only if {@link #isWithUpdateDateColumn()} ()}: {@link #getGetMaxUpdateDateQuery()}</li>
- * <li>Obtains query to get data to update: {@link #getGetDataToUpdateQuery()}</li>
- * </ul>
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.0
- */
-public class TuttiTableMetadata {
-
- protected static final String QUERY_SELECT_MAX_UPDATE = "SELECT max(update_date) FROM %s";
-
- protected static final String QUERY_SELECT_IDS = "SELECT %s FROM %s";
-
- protected static final String QUERY_INSERT = "INSERT INTO %s (%s) VALUES (%s)";
-
- protected static final String QUERY_UPDATE = "UPDATE %s SET %s WHERE %s = ?";
-
- protected final TableMetadata delegate;
-
- protected final Map<String, ColumnMetadata> columns;
-
- protected final String getExistingIdsQuery;
-
- protected final String insertQuery;
-
- protected final String updateQuery;
-
- protected final Set<String> pkNames;
-
- protected final boolean withUpdateDateColumn;
-
- protected final int pkIndex;
-
- private final String getMaxUpdateDateQuery;
-
- private final String getDataToUpdateQuery;
-
- public TuttiTableMetadata(TableMetadata delegate,
- DatabaseMetaData meta) {
-
- Preconditions.checkNotNull(delegate);
- this.delegate = delegate;
-
- try {
- Field field = TableMetadata.class.getDeclaredField("columns");
- field.setAccessible(true);
- this.columns = (Map) field.get(delegate);
- this.withUpdateDateColumn = columns.containsKey("update_date");
- this.pkNames = initPrimaryKeys(meta);
- Preconditions.checkNotNull(pkNames);
-
- this.pkIndex = createPkIndex();
- this.insertQuery = createInsertQuery();
- this.updateQuery = createUpdateQuery();
- this.getMaxUpdateDateQuery = createMaxUpdateDateQuery();
- this.getDataToUpdateQuery = createDataToUpdateQuery();
-
- this.getExistingIdsQuery = String.format(QUERY_SELECT_IDS, Joiner.on(',').join(pkNames), getName());
- } catch (Exception e) {
- throw new RuntimeException("Could not init " + this, e);
- }
- }
-
- public int getPkIndex() {
- return pkIndex;
- }
-
- public boolean isAssociationTable() {
- return CollectionUtils.isEmpty(pkNames);
- }
-
- public String getInsertQuery() {
- return insertQuery;
- }
-
- public String getUpdateQuery() {
- return updateQuery;
- }
-
- public String getGetExistingIdsQuery() {
- return getExistingIdsQuery;
- }
-
- public String getGetMaxUpdateDateQuery() {
- return getMaxUpdateDateQuery;
- }
-
- public String getGetDataToUpdateQuery() {
- return getDataToUpdateQuery;
- }
-
- public boolean isWithUpdateDateColumn() {
- return withUpdateDateColumn;
- }
-
- public int getColumnsCount() {
- return columns.size();
- }
-
- public SortedSet<String> getColumnNames() {
- return Sets.newTreeSet(columns.keySet());
- }
-
- public String getName() {
- return delegate.getName();
- }
-
- public ForeignKeyMetadata getForeignKeyMetadata(ForeignKey fk) {
- return delegate.getForeignKeyMetadata(fk);
- }
-
- public ColumnMetadata getColumnMetadata(String columnName) {
- return delegate.getColumnMetadata(columnName);
- }
-
- public String getSchema() {
- return delegate.getSchema();
- }
-
- public String getCatalog() {
- return delegate.getCatalog();
- }
-
- public ForeignKeyMetadata getForeignKeyMetadata(String keyName) {
- return delegate.getForeignKeyMetadata(keyName);
- }
-
- public IndexMetadata getIndexMetadata(String indexName) {
- return delegate.getIndexMetadata(indexName);
- }
-
- public Set<String> getPkNames() {
- return pkNames;
- }
-
- protected Set<String> initPrimaryKeys(DatabaseMetaData meta) throws SQLException {
-
- Set<String> result = Sets.newHashSet();
- ResultSet rs = meta.getPrimaryKeys(getCatalog(), getSchema(), getName());
- try {
-
- while (rs.next()) {
- result.add(rs.getString("COLUMN_NAME"));
- }
- rs.close();
- return ImmutableSet.copyOf(result);
- } finally {
- TuttiEntities.closeSilently(rs);
- }
- }
-
- protected String createInsertQuery() {
-
-
- StringBuilder queryParams = new StringBuilder();
- StringBuilder valueParams = new StringBuilder();
-
- for (String columnName : getColumnNames()) {
- queryParams.append(", ").append(columnName);
- valueParams.append(", ?");
- }
-
- String result = String.format(QUERY_INSERT,
- getName(),
- queryParams.substring(2),
- valueParams.substring(2));
- return result;
- }
-
- protected String createUpdateQuery() {
-
- String result = null;
-
- if (!isAssociationTable()) {
-
- StringBuilder updateParams = new StringBuilder();
-
- for (String columnName : getColumnNames()) {
- updateParams.append(", ").append(columnName).append(" = ?");
- }
-
- String pkColumnName = pkNames.iterator().next();
-
- result = String.format(QUERY_UPDATE,
- getName(),
- updateParams.substring(2),
- pkColumnName);
- }
- return result;
- }
-
- protected int createPkIndex() {
-
- int result = -1;
-
- if (!isAssociationTable()) {
- String pkColumnName = pkNames.iterator().next().toLowerCase();
-
- int i = 1;
-
- for (String columnName : getColumnNames()) {
- if (pkColumnName.equals(columnName)) {
- result = i;
- } else {
- i++;
- }
- }
- }
-
- return result;
- }
-
-
- protected String createMaxUpdateDateQuery() {
- String result = String.format(QUERY_SELECT_MAX_UPDATE, getName());
- return result;
- }
-
- protected String createDataToUpdateQuery() {
- StringBuilder queryParams = new StringBuilder("");
- for (String columnName : getColumnNames()) {
- queryParams.append(", ").append(columnName);
- }
- StringBuilder query = new StringBuilder("SELECT ");
- query.append(queryParams.substring(2));
- query.append(" FROM ").append(getName());
-
- if (isWithUpdateDateColumn()) {
-
- // add a filter
- query.append(" WHERE (update_date IS NULL OR update_date >= ?)");
- }
- String result = query.toString();
- return result;
- }
-
-}
Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -0,0 +1,271 @@
+package fr.ifremer.tutti.persistence.service.synchro;
+
+/*
+ * #%L
+ * Tutti :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import fr.ifremer.tutti.persistence.entities.TuttiEntities;
+import org.hibernate.mapping.ForeignKey;
+import org.hibernate.tool.hbm2ddl.ColumnMetadata;
+import org.hibernate.tool.hbm2ddl.ForeignKeyMetadata;
+import org.hibernate.tool.hbm2ddl.IndexMetadata;
+import org.hibernate.tool.hbm2ddl.TableMetadata;
+
+import java.lang.reflect.Field;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedSet;
+
+/**
+ * Overrides of the {@link TableMetadata} with some improvements:
+ * <ul>
+ * <li>Obtains number of columns via {@link #getColumnsCount()}</li>
+ * <li>Obtains all columns names available via {@link #getColumnNames()}</li>
+ * <li>Obtains primary key column names via {@link #getPkNames()}</li>
+ * </ul>
+ * <p/>
+ * And others methods used to synchronize referentials:
+ * <p/>
+ * <ul>
+ * <li>Obtains query to update a row of the table (column names order is the one introduced by method {@link #getColumnNames()}: {@link #getUpdateQuery()}</li>
+ * <li>Obtains query to insert a row in the table (column names order is the one introduced by method {@link #getColumnNames()}: {@link #getInsertQuery()}</li>
+ * </ul>
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public abstract class TuttiTableMetadata {
+
+ protected static final String QUERY_SELECT_MAX_UPDATE = "SELECT max(update_date) FROM %s";
+
+ protected static final String QUERY_INSERT = "INSERT INTO %s (%s) VALUES (%s)";
+
+ protected static final String QUERY_UPDATE = "UPDATE %s SET %s WHERE %s";
+
+ protected static final String QUERY_SELECT_PRIMARY_KEYS = "SELECT %s FROM %s";
+
+ protected static final String QUERY_SELECT_COUNT = "SELECT count(*) FROM %s";
+
+ protected final String existingPrimaryKeysQuery;
+
+ private final String maxUpdateDateQuery;
+
+ protected final String countQuery;
+
+ protected final TableMetadata delegate;
+
+ protected final Map<String, ColumnMetadata> columns;
+
+ protected final Set<String> pkNames;
+
+ protected final int[] pkIndexs;
+
+ protected final String insertQuery;
+
+ protected final String updateQuery;
+
+ protected final boolean withUpdateDateColumn;
+
+ public abstract String getDataToUpdateQueryWithNull();
+
+ public abstract String getDataToUpdateQuery();
+
+ public abstract boolean useUpdateDateColumn();
+
+ public TuttiTableMetadata(TableMetadata delegate,
+ DatabaseMetaData meta) {
+
+ Preconditions.checkNotNull(delegate);
+ this.delegate = delegate;
+
+ try {
+ Field field = TableMetadata.class.getDeclaredField("columns");
+ field.setAccessible(true);
+ this.columns = (Map) field.get(delegate);
+ this.withUpdateDateColumn = columns.containsKey("update_date");
+ this.pkNames = initPrimaryKeys(meta);
+ Preconditions.checkNotNull(pkNames);
+ this.pkIndexs = createPkIndex();
+
+ this.insertQuery = createInsertQuery();
+ this.updateQuery = createUpdateQuery();
+ this.maxUpdateDateQuery = String.format(QUERY_SELECT_MAX_UPDATE, getName());
+ this.existingPrimaryKeysQuery = String.format(QUERY_SELECT_PRIMARY_KEYS, Joiner.on(',').join(pkNames), getName());
+ this.countQuery = String.format(QUERY_SELECT_COUNT, getName());
+ } catch (Exception e) {
+ throw new RuntimeException("Could not init " + this, e);
+ }
+ }
+
+ public Set<String> getPkNames() {
+ return pkNames;
+ }
+
+ public boolean isWithUpdateDateColumn() {
+ return withUpdateDateColumn;
+ }
+
+ public int getColumnsCount() {
+ return columns.size();
+ }
+
+ public SortedSet<String> getColumnNames() {
+ return Sets.newTreeSet(columns.keySet());
+ }
+
+ public String getName() {
+ return delegate.getName();
+ }
+
+ public ForeignKeyMetadata getForeignKeyMetadata(ForeignKey fk) {
+ return delegate.getForeignKeyMetadata(fk);
+ }
+
+ public ColumnMetadata getColumnMetadata(String columnName) {
+ return delegate.getColumnMetadata(columnName);
+ }
+
+ public String getSchema() {
+ return delegate.getSchema();
+ }
+
+ public String getCatalog() {
+ return delegate.getCatalog();
+ }
+
+ public ForeignKeyMetadata getForeignKeyMetadata(String keyName) {
+ return delegate.getForeignKeyMetadata(keyName);
+ }
+
+ public IndexMetadata getIndexMetadata(String indexName) {
+ return delegate.getIndexMetadata(indexName);
+ }
+
+ public String getInsertQuery() {
+ return insertQuery;
+ }
+
+ public String getUpdateQuery() {
+ return updateQuery;
+ }
+
+ public String getExistingPrimaryKeysQuery() {
+ return existingPrimaryKeysQuery;
+ }
+
+ public String getMaxUpdateDateQuery() {
+ return maxUpdateDateQuery;
+ }
+
+ public String getCountQuery() {
+ return countQuery;
+ }
+
+ public int[] getPkIndexs() {
+ return pkIndexs;
+ }
+
+ protected Set<String> initPrimaryKeys(DatabaseMetaData meta) throws SQLException {
+
+ Set<String> result = Sets.newHashSet();
+ ResultSet rs = meta.getPrimaryKeys(getCatalog(), getSchema(), getName());
+ try {
+
+ while (rs.next()) {
+ result.add(rs.getString("COLUMN_NAME"));
+ }
+ rs.close();
+ return ImmutableSet.copyOf(result);
+ } finally {
+ TuttiEntities.closeSilently(rs);
+ }
+ }
+
+ protected int[] createPkIndex() {
+
+ int[] result = new int[pkNames.size()];
+
+ int pkI = 0;
+ for (String pkName : pkNames) {
+ String pkColumnName = pkName.toLowerCase();
+
+ int i = 1;
+
+ int index = -1;
+ for (String columnName : getColumnNames()) {
+ if (pkColumnName.equals(columnName)) {
+ index = i;
+ } else {
+ i++;
+ }
+ }
+ result[pkI++] = index;
+ }
+
+ return result;
+ }
+
+ protected String createInsertQuery() {
+
+ StringBuilder queryParams = new StringBuilder();
+ StringBuilder valueParams = new StringBuilder();
+
+ for (String columnName : getColumnNames()) {
+ queryParams.append(", ").append(columnName);
+ valueParams.append(", ?");
+ }
+
+ String result = String.format(QUERY_INSERT,
+ getName(),
+ queryParams.substring(2),
+ valueParams.substring(2));
+ return result;
+ }
+
+ protected String createUpdateQuery() {
+
+ StringBuilder updateParams = new StringBuilder();
+ StringBuilder pkParams = new StringBuilder();
+
+ for (String columnName : getColumnNames()) {
+ updateParams.append(", ").append(columnName).append(" = ?");
+ }
+
+ for (String columnName : getPkNames()) {
+ pkParams.append("AND ").append(columnName).append(" = ?");
+ }
+
+ String result = String.format(QUERY_UPDATE,
+ getName(),
+ updateParams.substring(2),
+ pkParams.substring(4));
+ return result;
+ }
+}
Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/TuttiTableMetadata.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/main/resources/tuttiBeanRefFactory.xml
===================================================================
--- trunk/tutti-persistence/src/main/resources/tuttiBeanRefFactory.xml 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/main/resources/tuttiBeanRefFactory.xml 2013-02-13 21:48:46 UTC (rev 410)
@@ -1,47 +1,47 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- #%L
- Tutti :: Persistence API
- $Id: beanRefFactory.xml 300 2013-02-02 14:11:58Z tchemit $
- $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/main/r… $
- %%
- Copyright (C) 2012 Ifremer
- %%
- 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%
- -->
-
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
- <import resource="classpath*:applicationContext-conf.xml"/>
-
- <bean id="TuttiBeanRefFactory"
- class="org.springframework.context.support.ClassPathXmlApplicationContext">
- <constructor-arg>
- <list>
- <value>classpath:applicationContext-conf.xml</value>
- <value>classpath:applicationContext-dataSource-${dataSource.type}.xml</value>
- <value>classpath:applicationContext-entities.xml</value>
- <value>classpath:applicationContext-service.xml</value>
- <value>classpath:applicationContext-service-tutti.xml</value>
- </list>
- </constructor-arg>
- </bean>
-
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ #%L
+ Tutti :: Persistence API
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2012 Ifremer
+ %%
+ 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%
+ -->
+
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+
+ <import resource="classpath*:applicationContext-conf.xml"/>
+
+ <bean id="TuttiBeanRefFactory"
+ class="org.springframework.context.support.ClassPathXmlApplicationContext">
+ <constructor-arg>
+ <list>
+ <value>classpath:applicationContext-conf.xml</value>
+ <value>classpath:applicationContext-dataSource-${dataSource.type}.xml</value>
+ <value>classpath:applicationContext-entities.xml</value>
+ <value>classpath:applicationContext-service.xml</value>
+ <value>classpath:applicationContext-service-tutti.xml</value>
+ </list>
+ </constructor-arg>
+ </bean>
+
</beans>
\ No newline at end of file
Property changes on: trunk/tutti-persistence/src/main/resources/tuttiBeanRefFactory.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseFixtures.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseFixtures.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseFixtures.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -66,18 +66,6 @@
return "57774";
}
- public int nbPmfm() {
- return 551;
- }
-
- public int nbGearClassification() {
- return 5;
- }
-
- public int nbGear() {
- return 192;
- }
-
public int refNbCaracteristic() {
return 482;
}
@@ -118,54 +106,6 @@
return 129;
}
- public int nbLocationClassification() {
- return 3;
- }
-
- public int nbLocationLevel() {
- return 87;
- }
-
- public int nbLocation() {
- return 58488;
- }
-
- public int nbTaxonomicLevel() {
- return 30;
- }
-
- public int nbReferenceTaxon() {
- return 8690;
- }
-
- public int nbTaxonName() {
- return 16901;
- }
-
- public int nbTaxonGroupType() {
- return 4;
- }
-
- public int nbTaxonGroup() {
- return 13357;
- }
-
- public int nbRoundWeightConversion() {
- return 3518;
- }
-
- public int nbWeightLegnthConversion() {
- return 2579;
- }
-
- public int nbVesselType() {
- return 10;
- }
-
- public int nbVessel() {
- return 193007;
- }
-
public int refNbFishingVessel() {
return 24805;
}
@@ -174,62 +114,10 @@
return 2;
}
- public int nbUserProfil() {
- return 4;
- }
-
- public int nbDepartment() {
- return 77;
- }
-
- public int nbPerson() {
- return 430;
- }
-
public int refNbPerson() {
return 123;
}
- public int nbQualitativeValue() {
- return 1196;
- }
-
- public int nbStatus() {
- return 4;
- }
-
- public int nbQualityFlag() {
- return 8;
- }
-
- public int nbUnit() {
- return 30;
- }
-
- public int nbAggregationLevel() {
- return 8;
- }
-
- public int nbParameterGroup() {
- return 11;
- }
-
- public int nbParameter() {
- return 300;
- }
-
- public int nbMatrix() {
- return 17;
- }
-
- public int nbFraction() {
- return 54;
- }
-
- public int nbMethod() {
- return 42;
- }
-
public String refSpeciesId() {
return "15461";
}
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -271,8 +271,13 @@
public Connection createEmptyDb(String dbDirectory,
String dbName) throws IOException, SQLException {
+ return createEmptyDb(dbDirectory, dbName, null);
+ }
+
+ public Connection createEmptyDb(String dbDirectory,
+ String dbName, Properties p) throws IOException, SQLException {
File externalDbFile = getResourceDirectory(dbDirectory);
- return createEmptyDb(externalDbFile, dbName);
+ return createEmptyDb(externalDbFile, dbName, p);
}
public static File getTestSpecificDirectory(Class<?> testClass,
@@ -303,6 +308,12 @@
public Connection createEmptyDb(File directory,
String dbName) throws SQLException, IOException {
+ return createEmptyDb(directory, dbName, null);
+ }
+
+ public Connection createEmptyDb(File directory,
+ String dbName, Properties p) throws SQLException, IOException {
+
if (log.isInfoEnabled()) {
log.info("Create new db at " + directory);
}
@@ -310,6 +321,9 @@
String user = "SA";
String password = "";
+ if (p != null) {
+ TuttiEntities.fillConnectionProperties(p, jdbcUrl, user, password);
+ }
File scriptFile = config.getConfig().getOptionAsFile(TUTTI_PERSISTENCE_JDBC_CREATE_SCRIPT);
Preconditions.checkNotNull("Could not find db script in configuration with key " + TUTTI_PERSISTENCE_JDBC_CREATE_SCRIPT);
Copied: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/DatabaseSynchroFixtures.java (from rev 400, trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseFixtures.java)
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/DatabaseSynchroFixtures.java (rev 0)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/DatabaseSynchroFixtures.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -0,0 +1,275 @@
+package fr.ifremer.tutti.persistence.service.synchro;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * 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%
+ */
+
+import com.google.common.collect.Maps;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.EnumMap;
+
+/**
+ * Fixtures for the allegro db.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class DatabaseSynchroFixtures {
+
+ protected final EnumMap<TuttiTable, Long> count;
+
+ public DatabaseSynchroFixtures(ReferentialSynchronizeHelper helper,
+ TuttiDatabaseMetadata db,
+ Connection connection) throws SQLException {
+ count = Maps.newEnumMap(TuttiTable.class);
+ for (TuttiTable table : TuttiTable.values()) {
+
+ String tableName = table.name();
+ TuttiTableMetadata tableMetadata = db.getTable(tableName);
+ long tableCount = helper.countTable(connection, tableMetadata);
+ count.put(table, tableCount);
+ }
+ }
+
+ public int count(TuttiTable table) {
+ return count.get(table).intValue();
+ }
+
+ public int nbPmfm() {
+ return count(TuttiTable.PMFM);
+ }
+
+ public int nbGearClassification() {
+ return count(TuttiTable.GEAR_CLASSIFICATION);
+ }
+
+ public int nbGear() {
+ return count(TuttiTable.GEAR);
+ }
+
+ public int nbLocationClassification() {
+ return count(TuttiTable.LOCATION_CLASSIFICATION);
+ }
+
+ public int nbLocationLevel() {
+ return count(TuttiTable.LOCATION_LEVEL);
+ }
+
+ public int nbLocation() {
+ return count(TuttiTable.LOCATION);
+ }
+
+ public int nbTaxonomicLevel() {
+ return count(TuttiTable.TAXONOMIC_LEVEL);
+ }
+
+ public int nbReferenceTaxon() {
+ return count(TuttiTable.REFERENCE_TAXON);
+ }
+
+ public int nbTaxonName() {
+ return count(TuttiTable.TAXON_NAME);
+ }
+
+ public int nbTaxonGroupType() {
+ return count(TuttiTable.TAXON_GROUP_TYPE);
+ }
+
+ public int nbTaxonGroup() {
+ return count(TuttiTable.TAXON_GROUP);
+ }
+
+ public int nbRoundWeightConversion() {
+ return count(TuttiTable.ROUND_WEIGHT_CONVERSION);
+ }
+
+ public int nbWeightLegnthConversion() {
+ return count(TuttiTable.WEIGHT_LENGTH_CONVERSION);
+ }
+
+ public int nbVesselType() {
+ return count(TuttiTable.VESSEL_TYPE);
+ }
+
+ public int nbVessel() {
+ return count(TuttiTable.VESSEL);
+ }
+
+ public int nbUserProfil() {
+ return count(TuttiTable.USER_PROFIL);
+ }
+
+ public int nbDepartment() {
+ return count(TuttiTable.DEPARTMENT);
+ }
+
+ public int nbPerson() {
+ return count(TuttiTable.PERSON);
+ }
+
+ public int nbQualitativeValue() {
+ return count(TuttiTable.QUALITATIVE_VALUE);
+ }
+
+ public int nbStatus() {
+ return count(TuttiTable.STATUS);
+ }
+
+ public int nbQualityFlag() {
+ return count(TuttiTable.QUALITY_FLAG);
+ }
+
+ public int nbUnit() {
+ return count(TuttiTable.UNIT);
+ }
+
+ public int nbAggregationLevel() {
+ return count(TuttiTable.AGGREGATION_LEVEL);
+ }
+
+ public int nbParameterGroup() {
+ return count(TuttiTable.PARAMETER_GROUP);
+ }
+
+ public int nbParameter() {
+ return count(TuttiTable.PARAMETER);
+ }
+
+ public int nbMatrix() {
+ return count(TuttiTable.MATRIX);
+ }
+
+ public int nbFraction() {
+ return count(TuttiTable.FRACTION);
+ }
+
+ public int nbMethod() {
+ return count(TuttiTable.METHOD);
+ }
+
+ public int nbLocationHierarchyException() {
+ return count(TuttiTable.LOCATION_HIERARCHY_EXCEPTION);
+ }
+
+ public int nbTaxonInformationHistory() {
+ return count(TuttiTable.TAXON_INFORMATION_HISTORY);
+ }
+
+ public int nbTaxonNameHistory() {
+ return count(TuttiTable.TAXON_NAME_HISTORY);
+ }
+
+ public int nbReferenceDocument() {
+ return count(TuttiTable.REFERENCE_DOCUMENT);
+ }
+
+ public int nbAuthor() {
+ return count(TuttiTable.AUTHOR);
+ }
+
+ public int nbCitation() {
+ return count(TuttiTable.CITATION);
+ }
+
+ public int nbTaxonGroupHistoricalRecord() {
+ return count(TuttiTable.TAXON_GROUP_HISTORICAL_RECORD);
+ }
+
+ public int nbUnitConversion() {
+ return count(TuttiTable.UNIT_CONVERSION);
+ }
+
+ public int nbOrderItem() {
+ return count(TuttiTable.ORDER_ITEM);
+ }
+
+ public int nbPrecisionType() {
+ return count(TuttiTable.PRECISION_TYPE);
+ }
+
+ public int nbNumericalPrecision() {
+ return count(TuttiTable.NUMERICAL_PRECISION);
+ }
+
+ public int nbPhotoType() {
+ return count(TuttiTable.PHOTO_TYPE);
+ }
+
+ public int nbObjectType() {
+ return count(TuttiTable.OBJECT_TYPE);
+ }
+
+ public int nbOrderType() {
+ return count(TuttiTable.ORDER_TYPE);
+ }
+
+ public int nbAnalysisInstrument() {
+ return count(TuttiTable.ANALYSIS_INSTRUMENT);
+ }
+
+ public int nbFraction2Matrix() {
+ return count(TuttiTable.FRACTION2MATRIX);
+ }
+
+ public int nbPmfm2QualitativeValue() {
+ return count(TuttiTable.PMFM2QUALITATIVE_VALUE);
+ }
+
+ public int nbGearClassificationAssociation() {
+ return count(TuttiTable.GEAR_CLASSIFICATION_ASSOCIATIO);
+ }
+
+ public int nbGearAssociation() {
+ return count(TuttiTable.GEAR_ASSOCIATION);
+ }
+
+ public int nbLocationAssociation() {
+ return count(TuttiTable.LOCATION_ASSOCIATION);
+ }
+
+ public int nbLocationHierarchy() {
+ return count(TuttiTable.LOCATION_HIERARCHY);
+ }
+
+ public int nbTaxonInformation() {
+ return count(TuttiTable.TAXON_INFORMATION);
+ }
+
+ public int nbVirtualComponent() {
+ return count(TuttiTable.VIRTUAL_COMPONENT);
+ }
+
+ public int nbTaxonGroupInformation() {
+ return count(TuttiTable.TAXON_GROUP_INFORMATION);
+ }
+
+ public int nbVesselRegistrationPeriod() {
+ return count(TuttiTable.VESSEL_REGISTRATION_PERIOD);
+ }
+
+ public int nbPerson2UserProfile() {
+ return count(TuttiTable.PERSON2USER_PROFIL);
+ }
+}
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java 2013-02-13 18:24:23 UTC (rev 409)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java 2013-02-13 21:48:46 UTC (rev 410)
@@ -24,7 +24,6 @@
* #L%
*/
-import fr.ifremer.tutti.persistence.DatabaseFixtures;
import fr.ifremer.tutti.persistence.DatabaseResource;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import fr.ifremer.tutti.persistence.service.TuttiPersistenceServiceLocator;
@@ -50,12 +49,11 @@
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
+import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
- * TODO
- *
* @author tchemit <chemit(a)codelutin.com>
* @since 1.0
*/
@@ -71,7 +69,6 @@
@Rule
public final TestName n = new TestName();
-
protected Connection externalConnection;
protected Connection internalConnection;
@@ -80,6 +77,8 @@
protected Dialect dialect;
+ protected Properties externalConnectionProperties;
+
protected Properties localConnectionProperties;
@Before
@@ -96,7 +95,7 @@
helper = null;
dialect = null;
localConnectionProperties = null;
-
+ externalConnectionProperties = null;
try {
if (internalConnection != null && !internalConnection.isClosed()) {
internalConnection.rollback();
@@ -201,6 +200,32 @@
getLastUpdateDate(TuttiTable.USER_PROFIL, internalDb, getSqlDate(2009, 6, 18));
getLastUpdateDate(TuttiTable.DEPARTMENT, internalDb, getSqlDate(2013, 1, 24));
getLastUpdateDate(TuttiTable.PERSON, internalDb, getSqlDate(2013, 1, 29));
+ getLastUpdateDate(TuttiTable.FRACTION2MATRIX, internalDb, null);
+ getLastUpdateDate(TuttiTable.PMFM2QUALITATIVE_VALUE, internalDb, null);
+ getLastUpdateDate(TuttiTable.GEAR_CLASSIFICATION_ASSOCIATIO, internalDb, getSqlDate(2012, 12, 18));
+ getLastUpdateDate(TuttiTable.GEAR_ASSOCIATION, internalDb, getSqlDate(2012, 12, 18));
+ getLastUpdateDate(TuttiTable.LOCATION_ASSOCIATION, internalDb, getSqlDate(2013, 1, 29));
+ getLastUpdateDate(TuttiTable.LOCATION_HIERARCHY, internalDb, null);
+ getLastUpdateDate(TuttiTable.LOCATION_HIERARCHY_EXCEPTION, internalDb, null);
+ getLastUpdateDate(TuttiTable.TAXON_INFORMATION, internalDb, getSqlDate(2012, 2, 13));
+ getLastUpdateDate(TuttiTable.TAXON_INFORMATION_HISTORY, internalDb, null);
+ getLastUpdateDate(TuttiTable.VIRTUAL_COMPONENT, internalDb, getSqlDate(2012, 2, 14));
+ getLastUpdateDate(TuttiTable.TAXON_GROUP_INFORMATION, internalDb, getSqlDate(2011, 3, 11));
+ getLastUpdateDate(TuttiTable.UNIT_CONVERSION, internalDb, getSqlDate(2011, 11, 21));
+ getLastUpdateDate(TuttiTable.VESSEL_REGISTRATION_PERIOD, internalDb, null);
+ getLastUpdateDate(TuttiTable.PERSON2USER_PROFIL, internalDb, null);
+ getLastUpdateDate(TuttiTable.TAXON_NAME_HISTORY, internalDb, getSqlDate(2013, 1, 21));
+ getLastUpdateDate(TuttiTable.REFERENCE_DOCUMENT, internalDb, getSqlDate(2011, 11, 4));
+ getLastUpdateDate(TuttiTable.AUTHOR, internalDb, null);
+ getLastUpdateDate(TuttiTable.CITATION, internalDb, getSqlDate(2012, 11, 30));
+ getLastUpdateDate(TuttiTable.TAXON_GROUP_HISTORICAL_RECORD, internalDb, getSqlDate(2013, 1, 16));
+ getLastUpdateDate(TuttiTable.ORDER_ITEM, internalDb, getSqlDate(2010, 5, 5));
+ getLastUpdateDate(TuttiTable.PRECISION_TYPE, internalDb, null);
+ getLastUpdateDate(TuttiTable.NUMERICAL_PRECISION, internalDb, null);
+ getLastUpdateDate(TuttiTable.PHOTO_TYPE, internalDb, getSqlDate(2010, 5, 26));
+ getLastUpdateDate(TuttiTable.OBJECT_TYPE, internalDb, getSqlDate(2013, 1, 7));
+ getLastUpdateDate(TuttiTable.ORDER_TYPE, internalDb, getSqlDate(2009, 10, 16));
+ getLastUpdateDate(TuttiTable.ANALYSIS_INSTRUMENT, internalDb, null);
// try it on a empty db (all values are to null)
@@ -216,7 +241,7 @@
}
@Test
- public void getExistingIds() throws SQLException, IOException {
+ public void getExistingPrimaryKeys() throws SQLException, IOException {
createInternalConnection();
@@ -224,43 +249,73 @@
helper.loadDatabaseMetadata(internalConnection, dialect);
Assert.assertNotNull(internalDb);
- DatabaseFixtures fixtures = dbResource.getFixtures();
- getExistingIds(TuttiTable.STATUS, fixtures.nbStatus());
- getExistingIds(TuttiTable.QUALITY_FLAG, fixtures.nbQualityFlag());
- getExistingIds(TuttiTable.UNIT, fixtures.nbUnit());
- getExistingIds(TuttiTable.AGGREGATION_LEVEL, fixtures.nbAggregationLevel());
- getExistingIds(TuttiTable.PARAMETER_GROUP, fixtures.nbParameterGroup());
- getExistingIds(TuttiTable.QUALITATIVE_VALUE, fixtures.nbQualitativeValue());
- getExistingIds(TuttiTable.PARAMETER, fixtures.nbParameter());
- getExistingIds(TuttiTable.MATRIX, fixtures.nbMatrix());
- getExistingIds(TuttiTable.FRACTION, fixtures.nbFraction());
- getExistingIds(TuttiTable.METHOD, fixtures.nbMethod());
- getExistingIds(TuttiTable.PMFM, fixtures.nbPmfm());
- getExistingIds(TuttiTable.GEAR_CLASSIFICATION, fixtures.nbGearClassification());
- getExistingIds(TuttiTable.GEAR, fixtures.nbGear());
- getExistingIds(TuttiTable.LOCATION_CLASSIFICATION, fixtures.nbLocationClassification());
- getExistingIds(TuttiTable.LOCATION_LEVEL, fixtures.nbLocationLevel());
- getExistingIds(TuttiTable.LOCATION, fixtures.nbLocation());
- getExistingIds(TuttiTable.TAXONOMIC_LEVEL, fixtures.nbTaxonomicLevel());
- getExistingIds(TuttiTable.REFERENCE_TAXON, fixtures.nbReferenceTaxon());
- getExistingIds(TuttiTable.TAXON_NAME, fixtures.nbTaxonName());
- getExistingIds(TuttiTable.TAXON_GROUP_TYPE, fixtures.nbTaxonGroupType());
- getExistingIds(TuttiTable.TAXON_GROUP, fixtures.nbTaxonGroup());
- getExistingIds(TuttiTable.ROUND_WEIGHT_CONVERSION, fixtures.nbRoundWeightConversion());
- getExistingIds(TuttiTable.WEIGHT_LENGTH_CONVERSION, fixtures.nbWeightLegnthConversion());
- getExistingIds(TuttiTable.VESSEL_TYPE, fixtures.nbVesselType());
- getExistingIds(TuttiTable.VESSEL, fixtures.nbVessel());
- getExistingIds(TuttiTable.USER_PROFIL, fixtures.nbUserProfil());
- getExistingIds(TuttiTable.DEPARTMENT, fixtures.nbDepartment());
- getExistingIds(TuttiTable.PERSON, fixtures.nbPerson());
+ DatabaseSynchroFixtures fixtures = new DatabaseSynchroFixtures(
+ helper, internalDb, internalConnection);
+ getExistingPrimaryKeys(TuttiTable.STATUS, fixtures.nbStatus());
+ getExistingPrimaryKeys(TuttiTable.QUALITY_FLAG, fixtures.nbQualityFlag());
+ getExistingPrimaryKeys(TuttiTable.UNIT, fixtures.nbUnit());
+ getExistingPrimaryKeys(TuttiTable.AGGREGATION_LEVEL, fixtures.nbAggregationLevel());
+ getExistingPrimaryKeys(TuttiTable.PARAMETER_GROUP, fixtures.nbParameterGroup());
+ getExistingPrimaryKeys(TuttiTable.QUALITATIVE_VALUE, fixtures.nbQualitativeValue());
+ getExistingPrimaryKeys(TuttiTable.PARAMETER, fixtures.nbParameter());
+ getExistingPrimaryKeys(TuttiTable.MATRIX, fixtures.nbMatrix());
+ getExistingPrimaryKeys(TuttiTable.FRACTION, fixtures.nbFraction());
+ getExistingPrimaryKeys(TuttiTable.METHOD, fixtures.nbMethod());
+ getExistingPrimaryKeys(TuttiTable.PMFM, fixtures.nbPmfm());
+ getExistingPrimaryKeys(TuttiTable.GEAR_CLASSIFICATION, fixtures.nbGearClassification());
+ getExistingPrimaryKeys(TuttiTable.GEAR, fixtures.nbGear());
+ getExistingPrimaryKeys(TuttiTable.LOCATION_CLASSIFICATION, fixtures.nbLocationClassification());
+ getExistingPrimaryKeys(TuttiTable.LOCATION_LEVEL, fixtures.nbLocationLevel());
+ getExistingPrimaryKeys(TuttiTable.LOCATION, fixtures.nbLocation());
+ getExistingPrimaryKeys(TuttiTable.TAXONOMIC_LEVEL, fixtures.nbTaxonomicLevel());
+ getExistingPrimaryKeys(TuttiTable.REFERENCE_TAXON, fixtures.nbReferenceTaxon());
+ getExistingPrimaryKeys(TuttiTable.TAXON_NAME, fixtures.nbTaxonName());
+ getExistingPrimaryKeys(TuttiTable.TAXON_GROUP_TYPE, fixtures.nbTaxonGroupType());
+ getExistingPrimaryKeys(TuttiTable.TAXON_GROUP, fixtures.nbTaxonGroup());
+ getExistingPrimaryKeys(TuttiTable.ROUND_WEIGHT_CONVERSION, fixtures.nbRoundWeightConversion());
+ getExistingPrimaryKeys(TuttiTable.WEIGHT_LENGTH_CONVERSION, fixtures.nbWeightLegnthConversion());
+ getExistingPrimaryKeys(TuttiTable.VESSEL_TYPE, fixtures.nbVesselType());
+ getExistingPrimaryKeys(TuttiTable.VESSEL, fixtures.nbVessel());
+ getExistingPrimaryKeys(TuttiTable.USER_PROFIL, fixtures.nbUserProfil());
+ getExistingPrimaryKeys(TuttiTable.DEPARTMENT, fixtures.nbDepartment());
+ getExistingPrimaryKeys(TuttiTable.PERSON, fixtures.nbPerson());
+
+ getExistingPrimaryKeys(TuttiTable.TAXON_NAME_HISTORY, fixtures.nbTaxonNameHistory());
+ getExistingPrimaryKeys(TuttiTable.REFERENCE_DOCUMENT, fixtures.nbReferenceDocument());
+ getExistingPrimaryKeys(TuttiTable.AUTHOR, fixtures.nbAuthor());
+ getExistingPrimaryKeys(TuttiTable.CITATION, fixtures.nbCitation());
+ getExistingPrimaryKeys(TuttiTable.TAXON_GROUP_HISTORICAL_RECORD, fixtures.nbTaxonGroupHistoricalRecord());
+ getExistingPrimaryKeys(TuttiTable.ORDER_ITEM, fixtures.nbOrderItem());
+ getExistingPrimaryKeys(TuttiTable.PRECISION_TYPE, fixtures.nbPrecisionType());
+ getExistingPrimaryKeys(TuttiTable.NUMERICAL_PRECISION, fixtures.nbNumericalPrecision());
+ getExistingPrimaryKeys(TuttiTable.PHOTO_TYPE, fixtures.nbPhotoType());
+ getExistingPrimaryKeys(TuttiTable.OBJECT_TYPE, fixtures.nbObjectType());
+ getExistingPrimaryKeys(TuttiTable.ORDER_TYPE, fixtures.nbOrderType());
+ getExistingPrimaryKeys(TuttiTable.ANALYSIS_INSTRUMENT, fixtures.nbAnalysisInstrument());
+
+ getExistingPrimaryKeys(TuttiTable.FRACTION2MATRIX, fixtures.nbFraction2Matrix());
+ getExistingPrimaryKeys(TuttiTable.PMFM2QUALITATIVE_VALUE, fixtures.nbPmfm2QualitativeValue());
+ getExistingPrimaryKeys(TuttiTable.GEAR_CLASSIFICATION_ASSOCIATIO, fixtures.nbGearClassificationAssociation());
+ getExistingPrimaryKeys(TuttiTable.GEAR_ASSOCIATION, fixtures.nbGearAssociation());
+ getExistingPrimaryKeys(TuttiTable.LOCATION_ASSOCIATION, fixtures.nbLocationAssociation());
+ getExistingPrimaryKeys(TuttiTable.LOCATION_HIERARCHY, fixtures.nbLocationHierarchy());
+ getExistingPrimaryKeys(TuttiTable.LOCATION_HIERARCHY_EXCEPTION, fixtures.nbLocationHierarchyException());
+ getExistingPrimaryKeys(TuttiTable.TAXON_INFORMATION, fixtures.nbTaxonInformation());
+ getExistingPrimaryKeys(TuttiTable.TAXON_INFORMATION_HISTORY, fixtures.nbTaxonInformationHistory());
+ getExistingPrimaryKeys(TuttiTable.VIRTUAL_COMPONENT, fixtures.nbVirtualComponent());
+ getExistingPrimaryKeys(TuttiTable.TAXON_GROUP_INFORMATION, fixtures.nbTaxonGroupInformation());
+ getExistingPrimaryKeys(TuttiTable.UNIT_CONVERSION, fixtures.nbUnitConversion());
+ getExistingPrimaryKeys(TuttiTable.VESSEL_REGISTRATION_PERIOD, fixtures.nbVesselRegistrationPeriod());
+ getExistingPrimaryKeys(TuttiTable.PERSON2USER_PROFIL, fixtures.nbPerson2UserProfile());
+
// try it on a empty db (nothing to synch)
// create a external empty db
createExternalDb();
for (TuttiTable tuttiTable : TuttiTable.values()) {
- getExistingIds(tuttiTable, true, 0);
+ getExistingPrimaryKeys(tuttiTable, true, 0);
}
}
@@ -275,7 +330,10 @@
helper.loadDatabaseMetadata(internalConnection, dialect);
Assert.assertNotNull(internalDb);
- DatabaseFixtures fixtures = dbResource.getFixtures();
+
+ DatabaseSynchroFixtures fixtures = new DatabaseSynchroFixtures(
+ helper, internalDb, internalConnection);
+
getDataToUpdate(TuttiTable.STATUS, internalDb, internalConnection, fromDate, fixtures.nbStatus());
getDataToUpdate(TuttiTable.QUALITY_FLAG, internalDb, internalConnection, fromDate, fixtures.nbQualityFlag());
getDataToUpdate(TuttiTable.UNIT, internalDb, internalConnection, fromDate, fixtures.nbUnit());
@@ -305,6 +363,33 @@
getDataToUpdate(TuttiTable.DEPARTMENT, internalDb, internalConnection, fromDate, fixtures.nbDepartment());
getDataToUpdate(TuttiTable.PERSON, internalDb, internalConnection, fromDate, fixtures.nbPerson());
+ getDataToUpdate(TuttiTable.FRACTION2MATRIX, internalDb, internalConnection, fromDate, fixtures.nbFraction2Matrix());
+ getDataToUpdate(TuttiTable.PMFM2QUALITATIVE_VALUE, internalDb, internalConnection, fromDate, fixtures.nbPmfm2QualitativeValue());
+ getDataToUpdate(TuttiTable.GEAR_CLASSIFICATION_ASSOCIATIO, internalDb, internalConnection, fromDate, fixtures.nbGearClassificationAssociation());
+ getDataToUpdate(TuttiTable.GEAR_ASSOCIATION, internalDb, internalConnection, fromDate, fixtures.nbGearAssociation());
+ getDataToUpdate(TuttiTable.LOCATION_ASSOCIATION, internalDb, internalConnection, fromDate, fixtures.nbLocationAssociation());
+ getDataToUpdate(TuttiTable.LOCATION_HIERARCHY, internalDb, internalConnection, fromDate, fixtures.nbLocationHierarchy());
+ getDataToUpdate(TuttiTable.LOCATION_HIERARCHY_EXCEPTION, internalDb, internalConnection, fromDate, fixtures.nbLocationHierarchyException());
+ getDataToUpdate(TuttiTable.TAXON_INFORMATION, internalDb, internalConnection, fromDate, fixtures.nbTaxonInformation());
+ getDataToUpdate(TuttiTable.TAXON_INFORMATION_HISTORY, internalDb, internalConnection, fromDate, fixtures.nbTaxonInformationHistory());
+ getDataToUpdate(TuttiTable.VIRTUAL_COMPONENT, internalDb, internalConnection, fromDate, fixtures.nbVirtualComponent());
+ getDataToUpdate(TuttiTable.TAXON_GROUP_INFORMATION, internalDb, internalConnection, fromDate, fixtures.nbTaxonGroupInformation());
+ getDataToUpdate(TuttiTable.UNIT_CONVERSION, internalDb, internalConnection, fromDate, fixtures.nbUnitConversion());
+ getDataToUpdate(TuttiTable.VESSEL_REGISTRATION_PERIOD, internalDb, internalConnection, fromDate, fixtures.nbVesselRegistrationPeriod());
+ getDataToUpdate(TuttiTable.PERSON2USER_PROFIL, internalDb, internalConnection, fromDate, fixtures.nbPerson2UserProfile());
+ getDataToUpdate(TuttiTable.TAXON_NAME_HISTORY, internalDb, internalConnection, fromDate, fixtures.nbTaxonNameHistory());
+ getDataToUpdate(TuttiTable.REFERENCE_DOCUMENT, internalDb, internalConnection, fromDate, fixtures.nbReferenceDocument());
+ getDataToUpdate(TuttiTable.AUTHOR, internalDb, internalConnection, fromDate, fixtures.nbAuthor());
+ getDataToUpdate(TuttiTable.CITATION, internalDb, internalConnection, fromDate, fixtures.nbCitation());
+ getDataToUpdate(TuttiTable.TAXON_GROUP_HISTORICAL_RECORD, internalDb, internalConnection, fromDate, fixtures.nbTaxonGroupHistoricalRecord());
+ getDataToUpdate(TuttiTable.ORDER_ITEM, internalDb, internalConnection, fromDate, fixtures.nbOrderItem());
+ getDataToUpdate(TuttiTable.PRECISION_TYPE, internalDb, internalConnection, fromDate, fixtures.nbPrecisionType());
+ getDataToUpdate(TuttiTable.NUMERICAL_PRECISION, internalDb, internalConnection, fromDate, fixtures.nbNumericalPrecision());
+ getDataToUpdate(TuttiTable.PHOTO_TYPE, internalDb, internalConnection, fromDate, fixtures.nbPhotoType());
+ getDataToUpdate(TuttiTable.OBJECT_TYPE, internalDb, internalConnection, fromDate, fixtures.nbObjectType());
+ getDataToUpdate(TuttiTable.ORDER_TYPE, internalDb, internalConnection, fromDate, fixtures.nbOrderType());
+ getDataToUpdate(TuttiTable.ANALYSIS_INSTRUMENT, internalDb, internalConnection, fromDate, fixtures.nbAnalysisInstrument());
+
// try it on a empty db (nothing to synch)
// create a external empty db
@@ -336,7 +421,9 @@
helper.loadDatabaseMetadata(externalConnection, dialect);
Assert.assertNotNull(externalDb);
- DatabaseFixtures fixtures = dbResource.getFixtures();
+ DatabaseSynchroFixtures fixtures = new DatabaseSynchroFixtures(
+ helper, internalDb, internalConnection);
+
updateTable(TuttiTable.STATUS, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbStatus(), 0);
updateTable(TuttiTable.QUALITY_FLAG, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbQualityFlag(), 0);
updateTable(TuttiTable.UNIT, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbUnit(), 0);
@@ -366,6 +453,34 @@
updateTable(TuttiTable.DEPARTMENT, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbDepartment(), 0);
updateTable(TuttiTable.PERSON, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbPerson(), 0);
+ updateTable(TuttiTable.FRACTION2MATRIX, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbFraction2Matrix(), 0);
+ updateTable(TuttiTable.PMFM2QUALITATIVE_VALUE, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbPmfm2QualitativeValue(), 0);
+ updateTable(TuttiTable.GEAR_CLASSIFICATION_ASSOCIATIO, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbGearClassificationAssociation(), 0);
+ updateTable(TuttiTable.GEAR_ASSOCIATION, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbGearAssociation(), 0);
+ updateTable(TuttiTable.LOCATION_ASSOCIATION, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbLocationAssociation(), 0);
+ updateTable(TuttiTable.LOCATION_HIERARCHY, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbLocationHierarchy(), 0);
+ updateTable(TuttiTable.LOCATION_HIERARCHY_EXCEPTION, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbLocationHierarchyException(), 0);
+ updateTable(TuttiTable.TAXON_INFORMATION, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbTaxonInformation(), 0);
+ updateTable(TuttiTable.TAXON_INFORMATION_HISTORY, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbTaxonInformationHistory(), 0);
+ updateTable(TuttiTable.VIRTUAL_COMPONENT, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbVirtualComponent(), 0);
+ updateTable(TuttiTable.TAXON_GROUP_INFORMATION, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbTaxonGroupInformation(), 0);
+ updateTable(TuttiTable.UNIT_CONVERSION, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbUnitConversion(), 0);
+ updateTable(TuttiTable.VESSEL_REGISTRATION_PERIOD, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbVesselRegistrationPeriod(), 0);
+ updateTable(TuttiTable.PERSON2USER_PROFIL, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbPerson2UserProfile(), 0);
+
+ updateTable(TuttiTable.TAXON_NAME_HISTORY, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbTaxonNameHistory(), 0);
+ updateTable(TuttiTable.REFERENCE_DOCUMENT, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbReferenceDocument(), 0);
+ updateTable(TuttiTable.AUTHOR, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbAuthor(), 0);
+ updateTable(TuttiTable.CITATION, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbCitation(), 0);
+ updateTable(TuttiTable.TAXON_GROUP_HISTORICAL_RECORD, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbTaxonGroupHistoricalRecord(), 0);
+ updateTable(TuttiTable.ORDER_ITEM, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbOrderItem(), 0);
+ updateTable(TuttiTable.PRECISION_TYPE, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbPrecisionType(), 0);
+ updateTable(TuttiTable.NUMERICAL_PRECISION, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbNumericalPrecision(), 0);
+ updateTable(TuttiTable.PHOTO_TYPE, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbPhotoType(), 0);
+ updateTable(TuttiTable.OBJECT_TYPE, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbObjectType(), 0);
+ updateTable(TuttiTable.ORDER_TYPE, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbOrderType(), 0);
+ updateTable(TuttiTable.ANALYSIS_INSTRUMENT, internalDb, internalConnection, externalConnection, fromDate, fixtures.nbAnalysisInstrument(), 0);
+
externalConnection.commit();
// externalConnection.rollback();
@@ -405,9 +520,37 @@
updateTable(TuttiTable.DEPARTMENT, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbDepartment());
updateTable(TuttiTable.PERSON, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbPerson());
+ updateTable(TuttiTable.FRACTION2MATRIX, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbFraction2Matrix());
+ updateTable(TuttiTable.PMFM2QUALITATIVE_VALUE, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbPmfm2QualitativeValue());
+ updateTable(TuttiTable.GEAR_CLASSIFICATION_ASSOCIATIO, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbGearClassificationAssociation());
+ updateTable(TuttiTable.GEAR_ASSOCIATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbGearAssociation());
+ updateTable(TuttiTable.LOCATION_ASSOCIATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbLocationAssociation());
+ updateTable(TuttiTable.LOCATION_HIERARCHY, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbLocationHierarchy());
+ updateTable(TuttiTable.LOCATION_HIERARCHY_EXCEPTION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbLocationHierarchyException());
+ updateTable(TuttiTable.TAXON_INFORMATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbTaxonInformation());
+ updateTable(TuttiTable.TAXON_INFORMATION_HISTORY, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbTaxonInformationHistory());
+ updateTable(TuttiTable.VIRTUAL_COMPONENT, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbVirtualComponent());
+ updateTable(TuttiTable.TAXON_GROUP_INFORMATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbTaxonGroupInformation());
+ updateTable(TuttiTable.UNIT_CONVERSION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbUnitConversion());
+ updateTable(TuttiTable.VESSEL_REGISTRATION_PERIOD, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbVesselRegistrationPeriod());
+ updateTable(TuttiTable.PERSON2USER_PROFIL, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbPerson2UserProfile());
+
+ updateTable(TuttiTable.TAXON_NAME_HISTORY, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbTaxonNameHistory());
+ updateTable(TuttiTable.REFERENCE_DOCUMENT, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbReferenceDocument());
+ updateTable(TuttiTable.AUTHOR, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbAuthor());
+ updateTable(TuttiTable.CITATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbCitation());
+ updateTable(TuttiTable.TAXON_GROUP_HISTORICAL_RECORD, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbTaxonGroupHistoricalRecord());
+ updateTable(TuttiTable.ORDER_ITEM, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbOrderItem());
+ updateTable(TuttiTable.PRECISION_TYPE, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbPrecisionType());
+ updateTable(TuttiTable.NUMERICAL_PRECISION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbNumericalPrecision());
+ updateTable(TuttiTable.PHOTO_TYPE, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbPhotoType());
+ updateTable(TuttiTable.OBJECT_TYPE, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbObjectType());
+ updateTable(TuttiTable.ORDER_TYPE, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbOrderType());
+ updateTable(TuttiTable.ANALYSIS_INSTRUMENT, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbAnalysisInstrument());
+
externalConnection.commit();
- // try to synch with a update date from next year (so nothing to synch, expect with no update_date table)
+ // try to synch with a update date from next year (so nothing to synch, expect with no update_date and association table)
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
@@ -449,6 +592,34 @@
updateTable(TuttiTable.DEPARTMENT, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
updateTable(TuttiTable.PERSON, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.FRACTION2MATRIX, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbFraction2Matrix());
+ updateTable(TuttiTable.PMFM2QUALITATIVE_VALUE, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbPmfm2QualitativeValue());
+ updateTable(TuttiTable.GEAR_CLASSIFICATION_ASSOCIATIO, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbGearClassificationAssociation());
+ updateTable(TuttiTable.GEAR_ASSOCIATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbGearAssociation());
+ updateTable(TuttiTable.LOCATION_ASSOCIATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbLocationAssociation());
+ updateTable(TuttiTable.LOCATION_HIERARCHY, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbLocationHierarchy());
+ updateTable(TuttiTable.LOCATION_HIERARCHY_EXCEPTION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbLocationHierarchyException());
+ updateTable(TuttiTable.TAXON_INFORMATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbTaxonInformation());
+ updateTable(TuttiTable.TAXON_INFORMATION_HISTORY, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbTaxonInformationHistory());
+ updateTable(TuttiTable.VIRTUAL_COMPONENT, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbVirtualComponent());
+ updateTable(TuttiTable.TAXON_GROUP_INFORMATION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbTaxonGroupInformation());
+ updateTable(TuttiTable.UNIT_CONVERSION, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbUnitConversion());
+ updateTable(TuttiTable.VESSEL_REGISTRATION_PERIOD, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbVesselRegistrationPeriod());
+ updateTable(TuttiTable.PERSON2USER_PROFIL, internalDb, internalConnection, externalConnection, fromDate, 0, fixtures.nbPerson2UserProfile());
+
+ updateTable(TuttiTable.TAXON_NAME_HISTORY, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.REFERENCE_DOCUMENT, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.AUTHOR, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.CITATION, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.TAXON_GROUP_HISTORICAL_RECORD, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.ORDER_ITEM, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.PRECISION_TYPE, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.NUMERICAL_PRECISION, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.PHOTO_TYPE, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.OBJECT_TYPE, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.ORDER_TYPE, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+ updateTable(TuttiTable.ANALYSIS_INSTRUMENT, internalDb, internalConnection, externalConnection, fromDate, 0, 0);
+
// add a aggregation level then synch
String query = "INSERT INTO AGGREGATION_LEVEL (ID, NAME, RANK_ORDER, UPDATE_DATE) VALUES (-1000, 'NAME', -1000, NULL)";
PreparedStatement statement = internalConnection.prepareStatement(query);
@@ -457,6 +628,79 @@
updateTable(TuttiTable.AGGREGATION_LEVEL, internalDb, internalConnection, externalConnection, fromDate, 1, 0);
}
+ @Test
+ public void synchronize() throws IOException, SQLException {
+
+ createInternalConnection();
+
+ TuttiDatabaseMetadata internalDb =
+ helper.loadDatabaseMetadata(internalConnection, dialect);
+ Assert.assertNotNull(internalDb);
+
+ createExternalDb();
+
+ // synchronize from main db to empty db
+
+ ReferentialSynchronizeResult result =
+ helper.synchronize(externalConnectionProperties,
+ localConnectionProperties,
+ dialect);
+
+ // same referentiel in both db
+ Assert.assertNotNull(result);
+
+ DatabaseSynchroFixtures fixturesExternal;
+ DatabaseSynchroFixtures fixturesInternal;
+
+ fixturesInternal = new DatabaseSynchroFixtures(
+ helper, internalDb, internalConnection);
+ fixturesExternal = new DatabaseSynchroFixtures(
+ helper, internalDb, externalConnection);
+
+ for (TuttiTable tuttiTable : TuttiTable.values()) {
+ String tableName = tuttiTable.name();
+ int nbInserts = result.getNbInserts(tableName);
+ int nbUpdates = result.getNbUpdates(tableName);
+ int expected = fixturesInternal.count(tuttiTable);
+ Assert.assertEquals(String.format("Table %s Should found %s inserts, but was only %s", tableName, expected, nbInserts), expected, nbInserts, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, 0, nbUpdates), 0, nbUpdates, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, fixturesInternal.count(tuttiTable), nbUpdates), fixturesInternal.count(tuttiTable), fixturesExternal.count(tuttiTable), 0);
+ }
+
+ // add a new status
+ internalConnection.prepareStatement("INSERT INTO STATUS(CODE, NAME) VALUES (4, 'NEW')").executeUpdate();
+
+ // add a new aggregation_level
+ internalConnection.prepareStatement("INSERT INTO AGGREGATION_LEVEL (ID, NAME, RANK_ORDER, UPDATE_DATE) VALUES (-1000, 'NAME', -1000, NULL)").executeUpdate();
+
+ // update a unit
+ PreparedStatement preparedStatement = internalConnection.prepareStatement("UPDATE UNIT SET SYMBOL = 'Auncun un?', UPDATE_DATE=? WHERE ID=1");
+ preparedStatement.setDate(1, new java.sql.Date(System.currentTimeMillis()));
+ preparedStatement.executeUpdate();
+
+ internalConnection.commit();
+
+ fixturesInternal = new DatabaseSynchroFixtures(
+ helper, internalDb, internalConnection);
+
+ result = helper.synchronize(externalConnectionProperties,
+ localConnectionProperties,
+ dialect);
+
+ fixturesExternal = new DatabaseSynchroFixtures(
+ helper, internalDb, externalConnection);
+
+ for (TuttiTable tuttiTable : TuttiTable.values()) {
+ String tableName = tuttiTable.name();
+
+ int internalCount = fixturesInternal.count(tuttiTable);
+ int externalCount = fixturesExternal.count(tuttiTable);
+
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, internalCount, externalCount), internalCount, externalCount, 0);
+ }
+
+ }
+
protected ResultSet getDataToUpdate(TuttiTable tuttiTable,
TuttiDatabaseMetadata db,
Connection connection,
@@ -486,7 +730,7 @@
int expectedInserts,
int expectedUpdates) throws SQLException {
- // internal is syncrho
+ // internal is synchro
ReferentialSynchronizeResult result = new ReferentialSynchronizeResult(
targetConnection.getMetaData().getURL(),
synchConnection.getMetaData().getURL()
@@ -501,8 +745,8 @@
if (dataToUpdate.next()) {
- Set<String> existingIds =
- helper.getExistingIds(targetConnection, table);
+ Set<List<String>> existingIds =
+ helper.getExistingPrimaryKeys(targetConnection, table);
ReferentialSynchronizeHelper.prepareSynch(targetConnection);
@@ -553,42 +797,48 @@
} else {
actual = helper.getLastUpdateDate(internalConnection, table);
}
+ if (log.isDebugEnabled()) {
+ if (actual == null) {
+ log.debug("getLastUpdateDate(TuttiTable." + tuttiTable.name() + ", internalDb, null);");
+ } else {
+ Calendar instance = Calendar.getInstance();
+ instance.setTime(actual);
+ log.debug("getLastUpdateDate(TuttiTable." + tuttiTable.name() + ", internalDb, getSqlDate(" + instance.get(Calendar.YEAR) + ", " + (1 + instance.get(Calendar.MONTH)) + ", " + instance.get(Calendar.DAY_OF_MONTH) + "));");
+ }
+ }
if (expected == null) {
Assert.assertNull(actual);
} else {
-
- if (log.isDebugEnabled()) {
- Calendar instance = Calendar.getInstance();
- instance.setTime(actual);
- log.debug("getLastUpdateDate(TuttiTable." + tuttiTable.name() + ", internalDb, getSqlDate(" + instance.get(Calendar.YEAR) + ", " + instance.get(Calendar.MONTH) + ", " + instance.get(Calendar.DAY_OF_MONTH) + "));");
- }
-
assertDate(expected, actual);
}
}
- protected void getExistingIds(TuttiTable tuttiTable,
- int expectedResult) throws SQLException {
- getExistingIds(tuttiTable, false, expectedResult);
+ protected void getExistingPrimaryKeys(TuttiTable tuttiTable,
+ int expectedResult) throws SQLException {
+ getExistingPrimaryKeys(tuttiTable, false, expectedResult);
}
- protected void getExistingIds(TuttiTable tuttiTable,
- boolean external,
- int expectedResult) throws SQLException {
+ protected void getExistingPrimaryKeys(TuttiTable tuttiTable,
+ boolean external,
+ int expectedResult) throws SQLException {
-
- TuttiDatabaseMetadata internalDb = helper.loadDatabaseMetadata(internalConnection, dialect);
+ TuttiDatabaseMetadata internalDb =
+ helper.loadDatabaseMetadata(internalConnection, dialect);
TuttiTableMetadata table = internalDb.getTable(tuttiTable.name());
Assert.assertNotNull(internalDb);
- Set<String> actual;
+ Set<List<String>> actual;
if (external) {
- actual = helper.getExistingIds(externalConnection, table);
+ actual = helper.getExistingPrimaryKeys(externalConnection, table);
} else {
- actual = helper.getExistingIds(internalConnection, table);
+ actual = helper.getExistingPrimaryKeys(internalConnection, table);
}
+ if (log.isDebugEnabled()) {
+ log.debug("getExistingPrimaryKeys(TuttiTable." + tuttiTable + ", " + actual.size() + ");");
+ }
Assert.assertNotNull(actual);
Assert.assertEquals(expectedResult, actual.size());
+
}
protected void assertTuttiDatabaseMetadata(TuttiDatabaseMetadata db) {
@@ -623,6 +873,34 @@
assertDatabaseMetadata(TuttiTable.USER_PROFIL, db, false, true);
assertDatabaseMetadata(TuttiTable.DEPARTMENT, db, false, true);
assertDatabaseMetadata(TuttiTable.PERSON, db, false, true);
+
+ assertDatabaseMetadata(TuttiTable.FRACTION2MATRIX, db, true, false);
+ assertDatabaseMetadata(TuttiTable.PMFM2QUALITATIVE_VALUE, db, true, false);
+ assertDatabaseMetadata(TuttiTable.GEAR_CLASSIFICATION_ASSOCIATIO, db, true, true);
+ assertDatabaseMetadata(TuttiTable.GEAR_ASSOCIATION, db, true, true);
+ assertDatabaseMetadata(TuttiTable.LOCATION_ASSOCIATION, db, true, true);
+ assertDatabaseMetadata(TuttiTable.LOCATION_HIERARCHY, db, true, false);
+ assertDatabaseMetadata(TuttiTable.LOCATION_HIERARCHY_EXCEPTION, db, true, false);
+ assertDatabaseMetadata(TuttiTable.TAXON_INFORMATION, db, true, true);
+ assertDatabaseMetadata(TuttiTable.TAXON_INFORMATION_HISTORY, db, true, true);
+ assertDatabaseMetadata(TuttiTable.VIRTUAL_COMPONENT, db, true, true);
+ assertDatabaseMetadata(TuttiTable.TAXON_GROUP_INFORMATION, db, true, true);
+ assertDatabaseMetadata(TuttiTable.VESSEL_REGISTRATION_PERIOD, db, true, false);
+ assertDatabaseMetadata(TuttiTable.PERSON2USER_PROFIL, db, true, false);
+
+ assertDatabaseMetadata(TuttiTable.TAXON_NAME_HISTORY, db, false, true);
+ assertDatabaseMetadata(TuttiTable.REFERENCE_DOCUMENT, db, false, true);
+ assertDatabaseMetadata(TuttiTable.AUTHOR, db, false, true);
+ assertDatabaseMetadata(TuttiTable.CITATION, db, false, true);
+ assertDatabaseMetadata(TuttiTable.TAXON_GROUP_HISTORICAL_RECORD, db, false, true);
+ assertDatabaseMetadata(TuttiTable.UNIT_CONVERSION, db, true, true);
+ assertDatabaseMetadata(TuttiTable.ORDER_ITEM, db, false, true);
+ assertDatabaseMetadata(TuttiTable.PRECISION_TYPE, db, false, true);
+ assertDatabaseMetadata(TuttiTable.NUMERICAL_PRECISION, db, false, true);
+ assertDatabaseMetadata(TuttiTable.PHOTO_TYPE, db, false, true);
+ assertDatabaseMetadata(TuttiTable.OBJECT_TYPE, db, false, true);
+ assertDatabaseMetadata(TuttiTable.ORDER_TYPE, db, false, true);
+ assertDatabaseMetadata(TuttiTable.ANALYSIS_INSTRUMENT, db, false, true);
}
protected void assertDatabaseMetadata(TuttiTable tableName,
@@ -631,7 +909,7 @@
boolean withUpdateDateColumn) {
TuttiTableMetadata table = db.getTable(tableName.name());
Assert.assertNotNull(table);
- if (!ObjectUtils.equals(associationTable, table.isAssociationTable())) {
+ if (!ObjectUtils.equals(associationTable, ReferentialSynchronizeHelper.IS_ASSOCIATION_TABLE.apply(table))) {
if (log.isWarnEnabled()) {
log.warn("[" + tableName + "] associationTable should be " + associationTable);
}
@@ -641,7 +919,7 @@
log.warn("[" + tableName + "] withUpdateDateColumn should be " + associationTable);
}
}
- Assert.assertEquals(associationTable, table.isAssociationTable());
+ Assert.assertEquals(associationTable, ReferentialSynchronizeHelper.IS_ASSOCIATION_TABLE.apply(table));
Assert.assertEquals(withUpdateDateColumn, table.isWithUpdateDateColumn());
}
@@ -668,7 +946,10 @@
}
protected void createExternalDb() throws IOException, SQLException {
- externalConnection = dbResource.createEmptyDb(n.getMethodName(), "newDb");
+ externalConnection = dbResource.createEmptyDb(
+ n.getMethodName(),
+ "newDb",
+ externalConnectionProperties = new Properties());
Assert.assertNotNull(externalConnection);
}
1
0
r409 - in trunk/tutti-ui-swing/src/main: java/fr/ifremer/tutti/ui/swing java/fr/ifremer/tutti/ui/swing/content/operation/catches java/fr/ifremer/tutti/ui/swing/content/operation/catches/species java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split java/fr/ifremer/tutti/ui/swing/util/editor resources/i18n
by kmorin@users.forge.codelutin.com 13 Feb '13
by kmorin@users.forge.codelutin.com 13 Feb '13
13 Feb '13
Author: kmorin
Date: 2013-02-13 19:24:23 +0100 (Wed, 13 Feb 2013)
New Revision: 409
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/409
Log:
continue weight computing
Added:
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java
Modified:
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUI.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.css
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.jaxx
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RemoveSpeciesBatchAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RemoveSpeciesSubBatchAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RenameSpeciesBatchAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchRowModel.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchTableModel.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUI.css
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUI.jaxx
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/CreateSpeciesBatchUI.css
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/SplitSpeciesBatchUIHandler.java
trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUI.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUI.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUI.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -117,6 +117,14 @@
* @since 0.1
*/
public static final String DECIMAL3_PATTERN = "\\d{0,6}|\\d{1,6}.\\d{0,3}";
+
+ /**
+ * Pattern to use for decimal numeric values with 3 decimal digits in
+ * editors.
+ *
+ * @since 0.1
+ */
+ public static final String DECIMALFORCE3_PATTERN = "\\d{0,6}|\\d{1,6}.\\d{3}";
/**
* Pattern to use for decimal numeric values with 2 digits + 3 decimal digits in
Added: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java (rev 0)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -0,0 +1,190 @@
+
+package fr.ifremer.tutti.ui.swing.content.operation.catches;
+
+import fr.ifremer.tutti.service.PersistenceService;
+import fr.ifremer.tutti.ui.swing.AbstractTuttiAction;
+import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SampleCategory;
+import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SpeciesBatchRowModel;
+import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SpeciesBatchUI;
+import fr.ifremer.tutti.ui.swing.content.operation.catches.species.frequency.SpeciesFrequencyRowModel;
+import java.awt.event.ActionEvent;
+import java.util.List;
+import javax.swing.JOptionPane;
+import org.apache.commons.collections.CollectionUtils;
+
+import static org.nuiton.i18n.I18n._;
+
+/**
+ *
+ * @author kmorin <kmorin(a)codelutin.com>
+ * @since 1.0
+ */
+public class ComputeWeightsAction extends AbstractTuttiAction<EditCatchesUIModel, EditCatchesUI, EditCatchesUIHandler> {
+
+ private static final long serialVersionUID = 1L;
+
+ public ComputeWeightsAction(EditCatchesUIHandler handler) {
+ super(handler,
+ "computeWeights",
+ "generate",
+ _("tutti.action.computeWeights"),
+ _("tutti.action.computeWeights.tip"),
+ true);
+ }
+
+ @Override
+ protected void doAction(ActionEvent event) throws Exception {
+ computeSpeciesBatches();
+ }
+
+ //------------------------------------------------------------------------//
+ //-- Internal methods --//
+ //------------------------------------------------------------------------//
+
+ protected void computeSpeciesBatches() {
+ PersistenceService persistenceService =
+ getService(PersistenceService.class);
+
+ Float totalSortedWeight = 0f;
+ Float totalUnsortedWeight = 0f;
+ SpeciesBatchUI ui = getUI().getSpeciesTabContent();
+ List<SpeciesBatchRowModel> roots = getUI().getSpeciesTabContent().getModel().getRows();
+ for (SpeciesBatchRowModel row : roots) {
+ if (row.isBatchRoot()) {
+ Float weight = computeSpeciesBatch(row);
+ if (weight == null) {
+ JOptionPane.showMessageDialog(
+ ui,
+ _("tutti.dialog.catches.species.computeWeight.error.message"),
+ _("tutti.dialog.catches.species.computeWeight.error.title"),
+ JOptionPane.ERROR_MESSAGE);
+ totalSortedWeight = null;
+ totalUnsortedWeight = null;
+ break;
+ }
+ if (persistenceService.isSortedQualitativeValue(row.getSortedUnsortedCategory().getCategoryValue())) {
+ totalSortedWeight += weight;
+ } else {
+ totalUnsortedWeight += weight;
+ }
+ }
+ }
+ Number inertWeight = ui.getSpeciesTotalInertWeightField().getModel();
+ if (inertWeight != null) {
+ totalSortedWeight += inertWeight.floatValue();
+ }
+ Number livingNotItemizedWeight = ui.getSpeciesTotalLivingNotItemizedWeightField().getModel();
+ if (livingNotItemizedWeight != null) {
+ totalSortedWeight += livingNotItemizedWeight.floatValue();
+ }
+
+ ui.getSpeciesTotalSampleSortedWeightField()
+ .setText(totalSortedWeight != null ? totalSortedWeight.toString() : "");
+
+ if (ui.getSpeciesTotalSortedWeightField().getModel() == null) {
+ ui.getSpeciesTotalSortedWeightField().setModel(totalSortedWeight);
+ }
+
+ ui.getSpeciesTotalUnsortedWeightField()
+ .setText(totalUnsortedWeight != null ? totalUnsortedWeight.toString() : "");
+ }
+
+ protected Float computeSpeciesBatch(SpeciesBatchRowModel row) {
+ SampleCategory finestCategory;
+ if (row.getAgeCategory().isValid()) {
+ finestCategory = row.getAgeCategory();
+
+ } else if (row.getMaturityCategory().isValid()) {
+ finestCategory = row.getMaturityCategory();
+
+ } else if (row.getSexCategory().isValid()) {
+ finestCategory = row.getSexCategory();
+
+ } else if (row.getSizeCategory().isValid()) {
+ finestCategory = row.getSizeCategory();
+
+ } else {
+ finestCategory = row.getSortedUnsortedCategory();
+ }
+
+ Float result = null;
+ Float categoryWeight = finestCategory.getCategoryWeight();
+ Float rowWeight = row.getWeight();
+
+ List<SpeciesBatchRowModel> children = row.getChildBatch();
+ // if the row is not a leaf
+ if (!row.isBatchLeaf()) {
+ Float sum = 0f;
+ // make the sum of the children weights
+ for (SpeciesBatchRowModel child : children) {
+ Float weight = computeSpeciesBatch(child);
+ if (weight == null) {
+ sum = null;
+ break;
+ }
+ sum += weight;
+ }
+
+ if (sum != null) {
+ if (categoryWeight == null) {
+ finestCategory.setComputedWeight(sum);
+ } else if (categoryWeight != sum) {
+ // handle error
+ }
+ result = sum;
+ }
+
+ } else {// the row is a leaf
+ List<SpeciesFrequencyRowModel> frequency = row.getFrequency();
+
+ if (CollectionUtils.isNotEmpty(frequency)) {
+ // if there are frequencies, then compute their weight
+ Float frequencyWeight = 0f;
+ for (SpeciesFrequencyRowModel frequencyModel : frequency) {
+ Float w = frequencyModel.getWeight();
+ if (w == null) {
+
+ // can't sum when a null value appears
+ frequencyWeight = null;
+ break;
+
+ } else if (frequencyWeight != null) {
+
+ // still can sum weights
+ frequencyWeight += w;
+ }
+ }
+
+ if (categoryWeight == null && rowWeight != null) {
+ //TODO handle error
+
+ } else if (categoryWeight == null && frequencyWeight != null) {
+ // if the category weight is null and the frequencies have a weight,
+ // then this weight is the result
+ finestCategory.setComputedWeight(frequencyWeight);
+ result = frequencyWeight;
+
+ } else if (frequencyWeight != null && frequencyWeight != categoryWeight) {
+ // if the weight of the frequencies is different from the category
+ // weight, then set the weight of the sample
+ if (rowWeight == null) {
+ row.setComputedWeight(frequencyWeight);
+
+ } else if (rowWeight != frequencyWeight) {
+ //TODO handle error
+ }
+ result = categoryWeight;
+
+
+ } else {
+ result = categoryWeight;
+ }
+
+ } else {
+ result = categoryWeight;
+ }
+ }
+
+ return result;
+ }
+}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.css
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.css 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.css 2013-02-13 18:24:23 UTC (rev 409)
@@ -259,4 +259,8 @@
#cancelButton {
_tuttiAction: {CancelEditCatchBatchAction.class};
+}
+
+#computeSpeciesBatchButton {
+ _tuttiAction: {ComputeWeightsAction.class};
}
\ No newline at end of file
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.jaxx
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.jaxx 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.jaxx 2013-02-13 18:24:23 UTC (rev 409)
@@ -350,6 +350,7 @@
constraints='BorderLayout.CENTER'>
<JButton id='cancelButton'/>
<JButton id='saveButton'/>
+ <JButton id='computeSpeciesBatchButton'/>
</JPanel>
</JPanel>
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RemoveSpeciesBatchAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RemoveSpeciesBatchAction.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RemoveSpeciesBatchAction.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -92,7 +92,7 @@
if (!selectedBatch.isBatchRoot()) {
// remove all sub batches of his parent
- SpeciesBatchRowModel parentBatch = selectedBatch.getBatchParent();
+ SpeciesBatchRowModel parentBatch = selectedBatch.getParentBatch();
// get parent row index
int parentIndex = tableModel.getRowIndex(parentBatch);
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RemoveSpeciesSubBatchAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RemoveSpeciesSubBatchAction.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RemoveSpeciesSubBatchAction.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -104,7 +104,7 @@
getModel().getRows().removeAll(rowToRemove);
// remove childs from parent batch
- parentBatch.setBatchChilds(null);
+ parentBatch.setChildBatch(null);
// refresh table from parent batch row index to the end
handler.getTableModel().fireTableDataChanged();
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RenameSpeciesBatchAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RenameSpeciesBatchAction.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/RenameSpeciesBatchAction.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -116,7 +116,7 @@
protected void changeChildrenSpecies(SpeciesBatchRowModel row,
Species species) {
row.setSpecies(species);
- List<SpeciesBatchRowModel> children = row.getBatchChild();
+ List<SpeciesBatchRowModel> children = row.getChildBatch();
if (children != null) {
for (SpeciesBatchRowModel child : children) {
changeChildrenSpecies(child, species);
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchRowModel.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchRowModel.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchRowModel.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -96,12 +96,14 @@
public static final String PROPERTY_FREQUENCY = "frequency";
public static final String PROPERTY_COMPUTED_NUMBER = "computedOrNotNumber";
+
+ public static final String PROPERTY_COMPUTED_WEIGHT = "computedOrNotWeight";
public static final String PROPERTY_ATTACHMENTS = "attachments";
- public static final String PROPERTY_BATCH_PARENT = "batchParent";
+ public static final String PROPERTY_PARENT_BATCH = "parentBatch";
- public static final String PROPERTY_BATCH_CHILD = "batchChild";
+ public static final String PROPERTY_CHILD_BATCH = "childBatch";
public static final String PROPERTY_BATCH_LEAF = "batchLeaf";
@@ -173,7 +175,8 @@
*
* @since 0.2
*/
- protected Float weight;
+ protected TuttiComputedOrNotData<Float> computedOrNotWeight =
+ new TuttiComputedOrNotData<Float>();
/**
* Total computed number (from frequencies).
@@ -210,7 +213,7 @@
* @see #isBatchRoot()
* @since 0.3
*/
- protected SpeciesBatchRowModel batchParent;
+ protected SpeciesBatchRowModel parentBatch;
/**
* List of child batches (can be null or empty if batch is a leaf).
@@ -218,7 +221,7 @@
* @see #isBatchLeaf()
* @since 0.3
*/
- protected List<SpeciesBatchRowModel> batchChild;
+ protected List<SpeciesBatchRowModel> childBatch;
protected static final Binder<SpeciesBatch, SpeciesBatchRowModel> fromBeanBinder =
BinderFactory.newBinder(SpeciesBatch.class,
@@ -463,34 +466,34 @@
//-- Navigation properties --//
//------------------------------------------------------------------------//
- public SpeciesBatchRowModel getBatchParent() {
- return batchParent;
+ public SpeciesBatchRowModel getParentBatch() {
+ return parentBatch;
}
- public void setBatchParent(SpeciesBatchRowModel batchParent) {
- Object oldValue = getBatchParent();
- this.batchParent = batchParent;
- firePropertyChange(PROPERTY_BATCH_PARENT, oldValue, batchParent);
+ public void setParentBatch(SpeciesBatchRowModel parentBatch) {
+ Object oldValue = getParentBatch();
+ this.parentBatch = parentBatch;
+ firePropertyChange(PROPERTY_PARENT_BATCH, oldValue, parentBatch);
firePropertyChange(PROPERTY_BATCH_ROOT, null, isBatchRoot());
}
- public List<SpeciesBatchRowModel> getBatchChild() {
- return batchChild;
+ public List<SpeciesBatchRowModel> getChildBatch() {
+ return childBatch;
}
- public void setBatchChilds(List<SpeciesBatchRowModel> batchChild) {
- this.batchChild = batchChild;
+ public void setChildBatch(List<SpeciesBatchRowModel> childBatch) {
+ this.childBatch = childBatch;
// force to propagate child changes
- firePropertyChange(PROPERTY_BATCH_CHILD, null, batchChild);
+ firePropertyChange(PROPERTY_CHILD_BATCH, null, childBatch);
firePropertyChange(PROPERTY_BATCH_LEAF, null, isBatchLeaf());
}
public boolean isBatchLeaf() {
- return CollectionUtils.isEmpty(batchChild);
+ return CollectionUtils.isEmpty(childBatch);
}
public boolean isBatchRoot() {
- return batchParent == null;
+ return parentBatch == null;
}
//------------------------------------------------------------------------//
@@ -508,12 +511,12 @@
}
public Float getWeight() {
- return weight;
+ return computedOrNotWeight.getData();
}
public void setWeight(Float weight) {
Object oldValue = getWeight();
- this.weight = weight;
+ this.computedOrNotWeight.setData(weight);
firePropertyChange(PROPERTY_WEIGHT, oldValue, weight);
}
@@ -567,7 +570,18 @@
firePropertyChange(PROPERTY_COMPUTED_NUMBER, oldValue,
computedNumber);
}
+
+ public Float getComputedWeight() {
+ return computedOrNotWeight.getComputedData();
+ }
+ public void setComputedWeight(Float computedWeight) {
+ Object oldValue = getComputedWeight();
+ computedOrNotWeight.setComputedData(computedWeight);
+ firePropertyChange(PROPERTY_COMPUTED_WEIGHT, oldValue,
+ computedWeight);
+ }
+
public TuttiComputedOrNotData<Integer> getComputedOrNotNumber() {
return computedOrNotNumber;
}
@@ -576,4 +590,12 @@
this.computedOrNotNumber = computedOrNotNumber;
}
+ public TuttiComputedOrNotData<Float> getComputedOrNotWeight() {
+ return computedOrNotWeight;
+ }
+
+ public void setComputedOrNotWeight(TuttiComputedOrNotData<Float> computedOrNotWeight) {
+ this.computedOrNotWeight = computedOrNotWeight;
+ }
+
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchTableModel.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchTableModel.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchTableModel.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -33,6 +33,7 @@
import javax.swing.table.TableColumnModel;
import java.util.Set;
+import org.apache.commons.logging.LogFactory;
import static org.nuiton.i18n.I18n.n_;
@@ -125,7 +126,7 @@
n_("tutti.table.species.batch.header.ageCategory"));
public static final ColumnIdentifier<SpeciesBatchRowModel> WEIGHT = ColumnIdentifier.newId(
- SpeciesBatchRowModel.PROPERTY_WEIGHT,
+ SpeciesBatchRowModel.PROPERTY_COMPUTED_WEIGHT,
n_("tutti.table.species.batch.header.weight"),
n_("tutti.table.species.batch.header.weight"));
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUI.css
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUI.css 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUI.css 2013-02-13 18:24:23 UTC (rev 409)
@@ -37,7 +37,8 @@
#speciesTotalWeightField {
property: speciesTotalWeight;
model: {model.getSpeciesTotalWeight()};
- numberPattern: {INT_6_DIGITS_PATTERN};
+ numberPattern: {DECIMALFORCE3_PATTERN};
+ useFloat: true;
}
#speciesTotalSortedWeightLabel {
@@ -48,7 +49,8 @@
#speciesTotalSortedWeightField {
property: speciesTotalSortedWeight;
model: {model.getSpeciesTotalSortedWeight()};
- numberPattern: {INT_6_DIGITS_PATTERN};
+ numberPattern: {DECIMALFORCE3_PATTERN};
+ useFloat: true;
}
#speciesTotalSampleSortedWeightLabel {
@@ -81,7 +83,8 @@
#speciesTotalInertWeightField {
property: speciesTotalInertWeight;
model: {model.getSpeciesTotalInertWeight()};
- numberPattern: {INT_6_DIGITS_PATTERN};
+ numberPattern: {DECIMALFORCE3_PATTERN};
+ useFloat: true;
}
#speciesTotalLivingNotItemizedWeightLabel {
@@ -92,7 +95,8 @@
#speciesTotalLivingNotItemizedWeightField {
property: speciesTotalLivingNotItemizedWeight;
model: {model.getSpeciesTotalLivingNotItemizedWeight()};
- numberPattern: {INT_6_DIGITS_PATTERN};
+ numberPattern: {DECIMALFORCE3_PATTERN};
+ useFloat: true;
}
#tablePopup {
@@ -138,12 +142,6 @@
enabled: {model.isCreateSpeciesBatchEnabled()};
}
-#computeSpeciesBatchButton {
- actionIcon: generate;
- mnemonic: E;
- text: "tutti.action.computeSpeciesBatch";
-}
-
#filterTablePane {
border: {new TitledBorder(null, "")};
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUI.jaxx
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUI.jaxx 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUI.jaxx 2013-02-13 18:24:23 UTC (rev 409)
@@ -156,9 +156,6 @@
<JRadioButton id='filterSpeciesBatchRootButton'
onActionPerformed='model.setTableViewMode(TableViewMode.ROOT)'/>
</JPanel>
- <JButton id='computeSpeciesBatchButton'
- constraints='BorderLayout.EAST'
- onActionPerformed='handler.computeSpeciesBatch()'/>
</JPanel>
</cell>
</row>
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUIHandler.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUIHandler.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -41,6 +41,7 @@
import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
import fr.ifremer.tutti.persistence.entities.referential.Species;
import fr.ifremer.tutti.service.DecoratorService;
+import fr.ifremer.tutti.ui.swing.AbstractTuttiAction;
import fr.ifremer.tutti.ui.swing.TuttiUI;
import fr.ifremer.tutti.ui.swing.content.operation.AbstractTuttiBatchTableUIHandler;
import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUI;
@@ -57,6 +58,7 @@
import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil;
import fr.ifremer.tutti.ui.swing.util.editor.AttachmentCellComponent;
import fr.ifremer.tutti.ui.swing.util.editor.LongTextCellComponent;
+import fr.ifremer.tutti.ui.swing.util.editor.TuttiComputedOrNotDataEditor;
import fr.ifremer.tutti.ui.swing.util.table.ColumnIdentifier;
import jaxx.runtime.JAXXUtil;
import jaxx.runtime.SwingUtil;
@@ -87,6 +89,10 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import javax.swing.border.LineBorder;
+import jaxx.runtime.swing.JAXXWidgetUtil;
+import jaxx.runtime.swing.editor.cell.NumberCellEditor;
+import org.apache.commons.lang.reflect.ConstructorUtils;
import static org.nuiton.i18n.I18n._;
import static org.nuiton.i18n.I18n.n_;
@@ -422,7 +428,7 @@
}
List<Species> speciesList = persistenceService.getAllSpecies(protocol);
-
+
SPECIES_UNIVERSE_CONTEXT_ENTRY.setContextValue(ui, speciesList);
FREQUENCY_LENGTH_CONTEXT_ENTRY.setContextValue(ui, lengthCaracterics);
}
@@ -586,9 +592,16 @@
{ // Weight column
- addFloatColumnToModel(columnModel,
- SpeciesBatchTableModel.WEIGHT,
- TuttiUI.DECIMAL3_PATTERN);
+ TuttiComputedOrNotDataEditor<Float> editor =
+ new TuttiComputedOrNotDataEditor(Float.class, false);
+ editor.getNumberEditor().setSelectAllTextOnError(true);
+ editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2));
+ editor.getNumberEditor().setNumberPattern(TuttiUI.DECIMALFORCE3_PATTERN);
+
+ addColumnToModel(columnModel,
+ editor,
+ null,
+ SpeciesBatchTableModel.WEIGHT);
}
{ // Number column (from frequencies)
@@ -809,7 +822,7 @@
}
// add new batches to his parent
- parentBatch.setBatchChilds(newBatches);
+ parentBatch.setChildBatch(newBatches);
//TODO Should only save parentBatch (will persist all his childs)
//saveRow(parentBatch);
@@ -829,128 +842,20 @@
}
public void updateTotalFromFrequencies(SpeciesBatchRowModel row) {
- Float totalWeight = null;
List<SpeciesFrequencyRowModel> frequency = row.getFrequency();
if (CollectionUtils.isNotEmpty(frequency)) {
Integer totalNumber = 0;
- totalWeight = 0f;
for (SpeciesFrequencyRowModel frequencyModel : frequency) {
- totalNumber += frequencyModel.getNumber();
- Float w = frequencyModel.getWeight();
- if (w == null) {
-
- // can't sum when a null value appears
- totalWeight = null;
- } else if (totalWeight != null) {
-
- // still can sum weights
- totalWeight += w;
+ if (frequencyModel.getNumber() != null) {
+ totalNumber += frequencyModel.getNumber();
}
}
row.setComputedNumber(totalNumber);
}
- SampleCategory finestCategory;
- if (row.getAgeCategory().isValid()) {
- finestCategory = row.getAgeCategory();
-
- } else if (row.getMaturityCategory().isValid()) {
- finestCategory = row.getMaturityCategory();
-
- } else if (row.getSexCategory().isValid()) {
- finestCategory = row.getSexCategory();
-
- } else if (row.getSizeCategory().isValid()) {
- finestCategory = row.getSizeCategory();
-
- } else {
- finestCategory = row.getSortedUnsortedCategory();
- }
- if (finestCategory.getCategoryWeight() == null) {
- finestCategory.setComputedWeight(totalWeight);
- }
-
}
- public void computeSpeciesBatch() {
- Float totalSortedWeight = 0f;
- Float totalUnsortedWeight = 0f;
- List<SpeciesBatchRowModel> roots = getModel().getRows();
- for (SpeciesBatchRowModel row : roots) {
- if (row.isBatchRoot()) {
- Float weight = computeSpeciesBatch(row);
- if (weight == null) {
- JOptionPane.showMessageDialog(
- ui,
- _("tutti.dialog.catches.species.computeWeight.error.message"),
- _("tutti.dialog.catches.species.computeWeight.error.title"),
- JOptionPane.ERROR_MESSAGE);
- totalSortedWeight = null;
- totalUnsortedWeight = null;
- break;
- }
- if (persistenceService.isSortedQualitativeValue(row.getSortedUnsortedCategory().getCategoryValue())) {
- totalSortedWeight += weight;
- } else {
- totalUnsortedWeight += weight;
- }
- }
- }
- ui.getSpeciesTotalSampleSortedWeightField()
- .setText(totalSortedWeight != null ? totalSortedWeight.toString() : "");
- ui.getSpeciesTotalUnsortedWeightField()
- .setText(totalUnsortedWeight != null ? totalUnsortedWeight.toString() : "");
- }
-
- //------------------------------------------------------------------------//
- //-- Internal methods --//
- //------------------------------------------------------------------------//
-
- protected Float computeSpeciesBatch(SpeciesBatchRowModel row) {
- Float sum = null;
- List<SpeciesBatchRowModel> children = row.getBatchChild();
- if (!row.isBatchLeaf()) {
- for (SpeciesBatchRowModel child : children) {
- Float weight = computeSpeciesBatch(child);
- if (weight == null) {
- return null;
- }
- sum += weight;
- }
- }
-
- SampleCategory finestCategory;
- if (row.getAgeCategory().isValid()) {
- finestCategory = row.getAgeCategory();
-
- } else if (row.getMaturityCategory().isValid()) {
- finestCategory = row.getMaturityCategory();
-
- } else if (row.getSexCategory().isValid()) {
- finestCategory = row.getSexCategory();
-
- } else if (row.getSizeCategory().isValid()) {
- finestCategory = row.getSizeCategory();
-
- } else {
- finestCategory = row.getSortedUnsortedCategory();
- }
- Float weight = finestCategory.getCategoryWeight();
- if (weight == null) {
- weight = finestCategory.getComputedWeight();
- }
- Float result;
- if (sum != null && weight == null) {
- finestCategory.setComputedWeight(sum);
- result = sum;
-
- } else {
- result = weight;
- }
- return result;
- }
-
protected void saveRows(Iterable<SpeciesBatchRowModel> rows) {
for (SpeciesBatchRowModel row : rows) {
saveRow(row);
@@ -970,6 +875,11 @@
SpeciesBatch catchBean = row.toBean();
catchBean.setFishingOperation(fishingOperation);
+
+ SpeciesBatchRowModel parent = row.getParentBatch();
+ if (parent != null) {
+ catchBean.setParentBatch(parent.toBean());
+ }
// apply sample category
catchBean.setSampleCategoryType(sampleCategory.getCategoryType().getType());
@@ -978,7 +888,7 @@
if (TuttiEntities.isNew(catchBean)) {
- SpeciesBatchRowModel batchParent = row.getBatchParent();
+ SpeciesBatchRowModel batchParent = row.getParentBatch();
String parentBatchId = null;
if (batchParent != null) {
@@ -994,7 +904,7 @@
row.setId(catchBean.getId());
} else {
if (log.isInfoEnabled()) {
- log.info("Persist existing species batch: " + catchBean.getId());
+ log.info("Persist existing species batch: " + catchBean.getId() + " (parent : " + catchBean.getParentBatch() + ")");
}
persistenceService.saveSpeciesBatch(catchBean);
}
@@ -1122,7 +1032,7 @@
if (!row.isBatchLeaf()) {
- for (SpeciesBatchRowModel batchChild : row.getBatchChild()) {
+ for (SpeciesBatchRowModel batchChild : row.getChildBatch()) {
collectedRows.add(batchChild);
collectChilds(batchChild, collectedRows);
}
@@ -1165,7 +1075,7 @@
SpeciesBatchRowModel childRow = loadSpeciesBatch(childBatch, newRow, rows);
batchChilds.add(childRow);
}
- newRow.setBatchChilds(batchChilds);
+ newRow.setChildBatch(batchChilds);
}
return newRow;
@@ -1194,7 +1104,7 @@
newRow.setSpecies(parentRow.getSpecies());
newRow.setSpeciesToConfirm(parentRow.getSpeciesToConfirm());
- newRow.setBatchParent(parentRow);
+ newRow.setParentBatch(parentRow);
newRow.setSpecies(parentRow.getSpecies());
if (sampleCategoryEnum != SampleCategoryEnum.sortedUnsorted) {
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIHandler.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIHandler.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -173,11 +173,9 @@
for (SpeciesProtocol sp : protocol.getSpecies()) {
speciesProtocol.put(sp.getSpeciesReferenceTaxonId(), sp);
}
-// speciesProtocol = TuttiEntities.splitById(protocol.getSpecies());
}
-
- //TODO Use protocol to have lengthStepCaracteristic to use (if any protocol)
+
initBeanComboBox(ui.getLengthStepCaracteristicComboBox(),
lengthStepCaracterics,
model.getLengthStepCaracteristic());
@@ -239,7 +237,7 @@
addFloatColumnToModel(columnModel,
SpeciesFrequencyTableModel.WEIGHT,
- TuttiUI.DECIMAL3_PATTERN);
+ TuttiUI.DECIMALFORCE3_PATTERN);
}
// create table model
@@ -251,10 +249,10 @@
table.setModel(tableModel);
table.setColumnModel(columnModel);
- installTableKeyListener(columnModel, table);
-
initTable(table);
+ installTableKeyListener(columnModel, table);
+
listenValidatorValid(ui.getValidator(), model);
}
@@ -413,32 +411,29 @@
lengthStep);
}
}
- } else {
+ }
+
+ if (lengthStepCaracteristic == null && protocol != null) {
- // not frequency, guess from protocol (if any)
+ Species species = speciesBatch.getSpecies();
- if (protocol != null) {
+ SpeciesProtocol sProtocol =
+ speciesProtocol.get(species.getReferenceTaxonId());
- Species species = speciesBatch.getSpecies();
+ if (sProtocol != null) {
- SpeciesProtocol sProtocol =
- speciesProtocol.get(species.getId());
- if (sProtocol != null) {
+ String lengthStepPmfmId = sProtocol.getLengthStepPmfmId();
+ lengthStepCaracteristic =
+ this.lengthStepCaracteristics.get(lengthStepPmfmId);
+ lengthStep = sProtocol.getLengthStep();
- String lengthStepPmfmId = sProtocol.getLengthStepPmfmId();
-
- lengthStepCaracteristic =
- this.lengthStepCaracteristics.get(lengthStepPmfmId);
- lengthStep = sProtocol.getLengthStep();
-
- if (log.isInfoEnabled()) {
- log.info("Use existing from protocol lengthStep " +
- "caracteristic / step " +
- decorate(lengthStepCaracteristic) + " / " +
- lengthStep);
- }
+ if (log.isInfoEnabled()) {
+ log.info("Use existing from protocol lengthStep " +
+ "caracteristic / step " +
+ decorate(lengthStepCaracteristic) + " / " +
+ lengthStep);
}
}
}
@@ -451,12 +446,6 @@
SpeciesFrequencyUIModel model = getModel();
- // connect model to validator
- ui.getValidator().setBean(model);
-
- model.setRows(editFrequency);
- model.setLengthStepCaracteristic(lengthStepCaracteristic);
-
SpeciesFrequencyUIModel.ConfigurationMode mode = SpeciesFrequencyUIModel.ConfigurationMode.SIMPLE;
if (protocol != null) {
Integer taxonId = speciesBatch.getSpecies().getReferenceTaxonId();
@@ -465,12 +454,19 @@
mode = SpeciesFrequencyUIModel.ConfigurationMode.SIMPLE_COUNTING;
}
}
- if (speciesBatch.getNumber() != null && editFrequency.size() != 1) {
+
+ if (speciesBatch.getNumber() != null && editFrequency.isEmpty()) {
mode = SpeciesFrequencyUIModel.ConfigurationMode.SIMPLE_COUNTING;
+ model.setSimpleCount(speciesBatch.getNumber());
}
model.setConfigurationMode(mode);
- model.setSimpleCount(speciesBatch.getNumber());
+ // connect model to validator
+ ui.getValidator().setBean(model);
+
+ model.setRows(editFrequency);
+ model.setLengthStepCaracteristic(lengthStepCaracteristic);
+
// keep batch (will be used to push back editing entry)
model.setBatch(speciesBatch);
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/CreateSpeciesBatchUI.css
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/CreateSpeciesBatchUI.css 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/CreateSpeciesBatchUI.css 2013-02-13 18:24:23 UTC (rev 409)
@@ -75,7 +75,7 @@
property: batchWeight;
model: {model.getBatchWeight()};
useFloat: true;
- numberPattern: {DECIMAL1_PATTERN};
+ numberPattern: {DECIMALFORCE3_PATTERN};
bean: {model};
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/SplitSpeciesBatchUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/SplitSpeciesBatchUIHandler.java 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/SplitSpeciesBatchUIHandler.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -382,7 +382,7 @@
addFloatColumnToModel(columnModel,
SplitSpeciesBatchTableModel.WEIGHT,
- TuttiUI.DECIMAL3_PATTERN);
+ TuttiUI.DECIMALFORCE3_PATTERN);
}
}
Added: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java (rev 0)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java 2013-02-13 18:24:23 UTC (rev 409)
@@ -0,0 +1,117 @@
+
+package fr.ifremer.tutti.ui.swing.util.editor;
+
+import fr.ifremer.tutti.ui.swing.util.TuttiComputedOrNotData;
+import java.awt.Component;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import javax.swing.AbstractCellEditor;
+import javax.swing.JTable;
+import javax.swing.SwingConstants;
+import javax.swing.SwingUtilities;
+import javax.swing.event.AncestorEvent;
+import javax.swing.event.AncestorListener;
+import javax.swing.table.TableCellEditor;
+import jaxx.runtime.swing.editor.NumberEditor;
+
+/**
+ * Editor for TuttiComputedOrNotData
+ *
+ * @author kmorin <kmorin(a)codelutin.com>
+ * @since 1.0
+ */
+public class TuttiComputedOrNotDataEditor<E extends Number> extends AbstractCellEditor
+ implements TableCellEditor, FocusListener, AncestorListener {
+
+ private static final long serialVersionUID = 1L;
+
+ protected final NumberEditor numberEditor;
+
+ protected TuttiComputedOrNotData<E> data;
+
+ /** constructor */
+ public TuttiComputedOrNotDataEditor(Class<E> type, boolean useSign) {
+ numberEditor = new NumberEditor();
+ numberEditor.getTextField().setHorizontalAlignment(SwingConstants.RIGHT);
+ numberEditor.getTextField().setBorder(null);
+ numberEditor.getTextField().addFocusListener(this);
+ numberEditor.getTextField().addAncestorListener(this);
+
+ numberEditor.setModelType(type);
+
+ numberEditor.setUseSign(useSign);
+ numberEditor.init();
+ }
+
+ @Override
+ public Component getTableCellEditorComponent(JTable table, Object value,
+ boolean isSelected, int row, int column) {
+
+ data = (TuttiComputedOrNotData<E>) value;
+ numberEditor.setModel(data.getData());
+
+ // Check nullity and set the text that will be selected with the current value
+ if (data.getData() != null) {
+ numberEditor.setModelText(String.valueOf(data.getData()));
+ }
+ return numberEditor;
+ }
+
+ public NumberEditor getNumberEditor() {
+ return numberEditor;
+ }
+
+ @Override
+ public TuttiComputedOrNotData<E> getCellEditorValue() {
+ return data;
+ }
+
+ @Override
+ public void focusGained(FocusEvent e) {
+ SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ numberEditor.getTextField().requestFocus();
+ numberEditor.getTextField().selectAll();
+ }
+ });
+ }
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ }
+
+ @Override
+ public void ancestorAdded(AncestorEvent event) {
+ SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ numberEditor.getTextField().requestFocus();
+ numberEditor.getTextField().selectAll();
+ }
+ });
+ }
+
+ @Override
+ public void ancestorRemoved(AncestorEvent event) {
+ }
+
+ @Override
+ public void ancestorMoved(AncestorEvent event) {
+ }
+
+ @Override
+ public boolean stopCellEditing() {
+ boolean result = super.stopCellEditing();
+ // Reset previous data to avoid keeping it on other cell edition
+ if (result) {
+ data.setData((E) numberEditor.getModel());
+
+ numberEditor.setModel(null);
+ // Use empty string, otherwise there is a NPE in NumberEditorHandler
+ numberEditor.setModelText("");
+
+ data = null;
+ }
+ return result;
+ }
+
+}
Modified: trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties
===================================================================
--- trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-02-12 18:44:24 UTC (rev 408)
+++ trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-02-13 18:24:23 UTC (rev 409)
@@ -27,7 +27,8 @@
tutti.action.cloneProtocol=Cloner
tutti.action.cloneProtocol.tip=Dupliquer le protocole sélectionné
tutti.action.close=Fermer
-tutti.action.computeSpeciesBatch=Elever les poids
+tutti.action.computeWeights=Elever les poids
+tutti.action.computeWeights.tip=Elever les poids
tutti.action.configuration=Configuration
tutti.action.configuration.tip=Configurer Tutti
tutti.action.createSpeciesBatch=Créer un lot pour une espèce
1
0
12 Feb '13
Author: tchemit
Date: 2013-02-12 19:44:24 +0100 (Tue, 12 Feb 2013)
New Revision: 408
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/408
Log:
i18n
Modified:
trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties
Modified: trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties
===================================================================
--- trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-02-12 18:40:17 UTC (rev 407)
+++ trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-02-12 18:44:24 UTC (rev 408)
@@ -149,10 +149,10 @@
tutti.dialog.askSaveBeforeLeaving.createFishingOperation=Le trait n'a pas été créé. Voulez-vous l'enregistrer ?
tutti.dialog.askSaveBeforeLeaving.message=Vous avez fait des modifications que vous n'avez pas enregistrées. Voulez-vous les enregistrer ?
tutti.dialog.askSaveBeforeLeaving.saveCatchBatch=La capture a été modifiée. Voulez-vous enregistrer les modifications ?
+tutti.dialog.askSaveBeforeLeaving.saveCruise=La campagne a été modifiée. Voulez-vous enregistrer les modifications ?
+tutti.dialog.askSaveBeforeLeaving.saveFishingOperation=Le trait a été modifié. Voulez-vous enregistrer les modifications ?
tutti.dialog.askSaveBeforeLeaving.saveProgram=La série de campagne a été modifiée. Voulez-vous enregistrer les modifications ?
-tutti.dialog.askSaveBeforeLeaving.saveCruise=La campagne a été modifiée. Voulez-vous enregistrer les modifications ?
tutti.dialog.askSaveBeforeLeaving.saveProtocol=Le protocol a été modifié. Voulez-vous enregistrer les modifications ?
-tutti.dialog.askSaveBeforeLeaving.saveFishingOperation=Le trait a été modifié. Voulez-vous enregistrer les modifications ?
tutti.dialog.askSaveBeforeLeaving.title=Modifications non enregistrées
tutti.dialog.catches.species.computeWeight.error.message=Erreur lors de l'élévation des poids
tutti.dialog.catches.species.computeWeight.error.title=Erreur
@@ -278,10 +278,10 @@
tutti.label.tab.catches=Captures
tutti.label.tab.catchesCaracteristics=Résumé
tutti.label.tab.fishingOperation=Trait
+tutti.label.tab.fishingOperation.environment=Environnement
+tutti.label.tab.fishingOperation.gearShooting=Mise en oeuvre de l'engin
tutti.label.tab.fishingOperation.general=Trait
tutti.label.tab.fishingOperation.hydrology=Paramètres hydrologiques
-tutti.label.tab.fishingOperation.environment=Environnement
-tutti.label.tab.fishingOperation.gearShooting=Mise en oeuvre de l'engin
tutti.label.tab.macroDechet=Macro déchets
tutti.label.tab.observationIndividuel=Observations individuelles
tutti.label.tab.plancton=Plancton
1
0
r407 - in trunk/tutti-ui-swing/src/main: java/fr/ifremer/tutti/ui/swing java/fr/ifremer/tutti/ui/swing/content/cruise java/fr/ifremer/tutti/ui/swing/content/operation java/fr/ifremer/tutti/ui/swing/content/operation/catches java/fr/ifremer/tutti/ui/swing/content/program java/fr/ifremer/tutti/ui/swing/content/protocol resources/i18n
by tchemit@users.forge.codelutin.com 12 Feb '13
by tchemit@users.forge.codelutin.com 12 Feb '13
12 Feb '13
Author: tchemit
Date: 2013-02-12 19:40:17 +0100 (Tue, 12 Feb 2013)
New Revision: 407
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/407
Log:
refs #1845: [ERGO] - Principe d'enregistrement lors de la fermeture de l'?\195?\169cran (on doit aussi g?\195?\169rer le cas de mod?\195?\168le invalide)
Modified:
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/AbstractTuttiUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/cruise/EditCruiseUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/FishingOperationsUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/program/EditProgramUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/EditProtocolUIHandler.java
trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/AbstractTuttiUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/AbstractTuttiUIHandler.java 2013-02-12 18:38:26 UTC (rev 406)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/AbstractTuttiUIHandler.java 2013-02-12 18:40:17 UTC (rev 407)
@@ -261,24 +261,23 @@
SwingUtil.getParentContainer(ui, JDialog.class).setVisible(false);
}
- public int askSaveBeforeLeaving(Component parent) {
+ public int askSaveBeforeLeaving(String message) {
int i = JOptionPane.showConfirmDialog(
- parent,
- _("tutti.dialog.askSaveBeforeLeaving.message"),
+ getContext().getMainUI(),
+ message,
_("tutti.dialog.askSaveBeforeLeaving.title"),
JOptionPane.YES_NO_CANCEL_OPTION);
return i;
}
- public int askSaveBeforeLeaving(String message) {
+ public int askCancelEditBeforeLeaving(String message) {
int i = JOptionPane.showConfirmDialog(
getContext().getMainUI(),
message,
- _("tutti.dialog.askSaveBeforeLeaving.title"),
- JOptionPane.YES_NO_CANCEL_OPTION);
+ _("tutti.dialog.askCancelEditBeforeLeaving.title"),
+ JOptionPane.YES_NO_OPTION);
return i;
}
-
//------------------------------------------------------------------------//
//-- Internal methods --//
//------------------------------------------------------------------------//
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/cruise/EditCruiseUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/cruise/EditCruiseUIHandler.java 2013-02-12 18:38:26 UTC (rev 406)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/cruise/EditCruiseUIHandler.java 2013-02-12 18:40:17 UTC (rev 407)
@@ -46,6 +46,8 @@
import java.beans.PropertyChangeListener;
import java.util.List;
+import static org.nuiton.i18n.I18n._;
+
/**
* Handler of UI {@link EditCruiseUI}.
*
@@ -258,7 +260,7 @@
public boolean canCloseUI(TuttiScreen nextScreen) {
boolean result = true;
if (getModel().isModify()) {
- int answer = askSaveBeforeLeaving(ui);
+ int answer = askSaveBeforeLeaving(_("tutti.dialog.askSaveBeforeLeaving.saveCruise"));
result = answer == JOptionPane.NO_OPTION;
if (answer == JOptionPane.YES_OPTION) {
ActionEvent event = new ActionEvent(nextScreen, nextScreen.ordinal(), null);
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationUIHandler.java 2013-02-12 18:38:26 UTC (rev 406)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationUIHandler.java 2013-02-12 18:40:17 UTC (rev 407)
@@ -26,6 +26,7 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
+import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import fr.ifremer.tutti.persistence.entities.data.Cruise;
import fr.ifremer.tutti.persistence.entities.data.Program;
import fr.ifremer.tutti.persistence.entities.referential.FishingOperationLocation;
@@ -57,6 +58,8 @@
import java.util.Date;
import java.util.List;
+import static org.nuiton.i18n.I18n._;
+
/**
* Handler for UI {@link EditFishingOperationUI}.
*
@@ -91,31 +94,31 @@
}
};
-
+
private final PropertyChangeListener coordinatePropertiesListener = new PropertyChangeListener() {
private List<String> properties = Lists.newArrayList(
- EditFishingOperationUIModel.PROPERTY_FISHING_OPERATION_RECTILIGNE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE_DECIMAL_MINUTE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE_DEGREE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE_MINUTE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE_SECOND,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE_DECIMAL_MINUTE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE_DEGREE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE_MINUTE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE_SECOND,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE_DECIMAL_MINUTE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE_DEGREE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE_MINUTE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE_SECOND,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE_DECIMAL_MINUTE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE_DEGREE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE_MINUTE,
- EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE_SECOND
+ EditFishingOperationUIModel.PROPERTY_FISHING_OPERATION_RECTILIGNE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE_DECIMAL_MINUTE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE_DEGREE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE_MINUTE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LATITUDE_SECOND,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE_DECIMAL_MINUTE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE_DEGREE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE_MINUTE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_END_LONGITUDE_SECOND,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE_DECIMAL_MINUTE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE_DEGREE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE_MINUTE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LATITUDE_SECOND,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE_DECIMAL_MINUTE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE_DEGREE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE_MINUTE,
+ EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_LONGITUDE_SECOND
);
@Override
@@ -328,21 +331,67 @@
@Override
public boolean onHideTab(int currentIndex, int newIndex) {
- boolean result = !isAModelModified();
- if (!result) {
- int answer = askSaveBeforeLeaving(ui);
- ActionEvent event = new ActionEvent(this, newIndex, null);
- switch (answer) {
- case JOptionPane.OK_OPTION:
- doAction(ui.getSaveButton(), event);
- result = true;
- break;
+ boolean result;
+ if (isAModelModified()) {
- case JOptionPane.NO_OPTION:
- doAction(ui.getCancelButton(), event);
- result = true;
- break;
+ // something was modified
+
+ EditFishingOperationUIModel model = getModel();
+
+ if (model.isValid()) {
+
+ // ask if user want to save, do not save or cancel action
+
+ String message;
+
+ if (TuttiEntities.isNew(model.getFishingOperation())) {
+ message = _("tutti.dialog.askSaveBeforeLeaving.createFishingOperation");
+ } else {
+ message = _("tutti.dialog.askSaveBeforeLeaving.saveFishingOperation");
+ }
+
+ int answer = askSaveBeforeLeaving(message);
+ ActionEvent event = new ActionEvent(this, newIndex, null);
+ switch (answer) {
+ case JOptionPane.OK_OPTION:
+ doAction(ui.getSaveButton(), event);
+ result = true;
+ break;
+
+ case JOptionPane.NO_OPTION:
+ doAction(ui.getCancelButton(), event);
+ result = true;
+ break;
+ default:
+
+ // other case, use cancel action
+ result = false;
+ }
+ } else {
+
+ // model is not valid, ask user to continue or not
+
+ int answer = askCancelEditBeforeLeaving(
+ _("tutti.dialog.askCancelEditBeforeLeaving.cancelEditFishingOperation"));
+ switch (answer) {
+ case JOptionPane.YES_OPTION:
+
+ // ok will revert any modification
+ ActionEvent event = new ActionEvent(this, newIndex, null);
+ doAction(ui.getCancelButton(), event);
+ result = true;
+ break;
+ default:
+
+ // other case, use cancel action
+ result = false;
+ }
}
+
+ } else {
+
+ // model not modify, can change tab
+ result = true;
}
return result;
}
@@ -469,7 +518,7 @@
public void installStartDateListener() {
getModel().addPropertyChangeListener(EditFishingOperationUIModel.PROPERTY_GEAR_SHOOTING_START_DATE, startDateListener);
}
-
+
public void uninstallCoordinatesListener() {
getModel().removePropertyChangeListener(coordinatePropertiesListener);
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/FishingOperationsUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/FishingOperationsUIHandler.java 2013-02-12 18:38:26 UTC (rev 406)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/FishingOperationsUIHandler.java 2013-02-12 18:40:17 UTC (rev 407)
@@ -64,10 +64,6 @@
persistenceService = context.getService(PersistenceService.class);
}
- public FishingOperationsUI getUi() {
- return ui;
- }
-
@Override
public void beforeInitUI() {
@@ -232,4 +228,23 @@
return ui.getTabPane();
}
+ public boolean isFishingOperationModified() {
+ return getModel().getEditFishingOperation() != null &&
+ getUI().getFishingOperationTabContent().getModel().isModify();
+ }
+
+ public boolean isFishingOperationValid() {
+ return getModel().getEditFishingOperation() != null &&
+ getUI().getFishingOperationTabContent().getModel().isValid();
+ }
+
+ public boolean isCatchBatchModified() {
+ return getModel().getEditFishingOperation() != null &&
+ getUI().getCatchesTabContent().getModel().isModify();
+ }
+
+ public boolean isCatchBatchValid() {
+ return getModel().getEditFishingOperation() != null &&
+ getUI().getCatchesTabContent().getModel().isValid();
+ }
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUIHandler.java 2013-02-12 18:38:26 UTC (rev 406)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUIHandler.java 2013-02-12 18:40:17 UTC (rev 407)
@@ -39,6 +39,7 @@
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
+import java.awt.event.ActionEvent;
import static org.nuiton.i18n.I18n._;
import static org.nuiton.i18n.I18n.n_;
@@ -77,9 +78,10 @@
private final TuttiBeanMonitor<EditCatchesUIModel> catchBatchMonitor;
protected final FishingOperationsUI parentUi;
+
public EditCatchesUIHandler(FishingOperationsUI parentUi, EditCatchesUI ui) {
super(parentUi.getHandler().getContext(), ui);
- this.parentUi=parentUi;
+ this.parentUi = parentUi;
// this.persistenceService = context.getService(PersistenceService.class);
this.catchBatchMonitor = new TuttiBeanMonitor<EditCatchesUIModel>(
EditCatchesUIModel.PROPERTY_SPECIES_TOTAL_WEIGHT,
@@ -151,33 +153,62 @@
// (I do not even know why it is set to modified and have no time
// before the demo)
EditCatchesUIModel model = getModel();
- boolean result = model.isValid();
+ boolean result;
if (model.isModify()) {
- int answer = askSaveBeforeLeaving(getUI());
- switch (answer) {
- case JOptionPane.OK_OPTION:
- // persist catch batch
- doAction(getUI().getSaveButton(), null);
+ if (model.isValid()) {
- result = true;
- break;
+ // ask user to save, do not save or cancel action
+ int answer = askSaveBeforeLeaving(
+ _("tutti.dialog.askSaveBeforeLeaving.saveCatchBatch"));
+ switch (answer) {
+ case JOptionPane.OK_OPTION:
- case JOptionPane.NO_OPTION:
+ // persist catch batch
+ doAction(getUI().getSaveButton(), null);
- // won't save modification
- // so since we will edit a new operation, nothing to do here
+ result = true;
+ break;
- // persist catch batch
- doAction(getUI().getCancelButton(), null);
+ case JOptionPane.NO_OPTION:
- result = true;
- break;
- default:
+ // won't save modification
+ // so since we will edit a new operation, nothing to do here
- // other case, use cancel action
- result = false;
+ // persist catch batch
+ doAction(getUI().getCancelButton(), null);
+
+ result = true;
+ break;
+ default:
+
+ // other case, use cancel action
+ result = false;
+ }
+ } else {
+
+ // model is not valid, ask user to loose modification or cancel
+ int answer = askCancelEditBeforeLeaving(
+ _("tutti.dialog.askCancelEditBeforeLeaving.cancelEditCatchBatch"));
+ switch (answer) {
+ case JOptionPane.YES_OPTION:
+
+ // ok will revert any modification
+ ActionEvent event = new ActionEvent(this, newIndex, null);
+ doAction(ui.getCancelButton(), event);
+ result = true;
+ break;
+ default:
+
+ // other case, use cancel action
+ result = false;
+ }
}
+
+ } else {
+
+ // model not modify, can change tab
+ result = true;
}
return result;
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/program/EditProgramUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/program/EditProgramUIHandler.java 2013-02-12 18:38:26 UTC (rev 406)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/program/EditProgramUIHandler.java 2013-02-12 18:40:17 UTC (rev 407)
@@ -38,6 +38,8 @@
import java.awt.event.ActionEvent;
import java.util.List;
+import static org.nuiton.i18n.I18n._;
+
/**
* Handler of UI {@link EditProgramUI}.
*
@@ -132,7 +134,7 @@
public boolean canCloseUI(TuttiScreen nextScreen) {
boolean result = true;
if (getModel().isModify()) {
- int answer = askSaveBeforeLeaving(ui);
+ int answer = askSaveBeforeLeaving(_("tutti.dialog.askSaveBeforeLeaving.saveProgram"));
result = answer == JOptionPane.NO_OPTION;
if (answer == JOptionPane.YES_OPTION) {
ActionEvent event = new ActionEvent(nextScreen, nextScreen.ordinal(), null);
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/EditProtocolUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/EditProtocolUIHandler.java 2013-02-12 18:38:26 UTC (rev 406)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/EditProtocolUIHandler.java 2013-02-12 18:40:17 UTC (rev 407)
@@ -63,7 +63,9 @@
import java.util.List;
import java.util.Map;
+import static org.nuiton.i18n.I18n._;
+
/**
* @author tchemit <chemit(a)codelutin.com>
* @since 0.3
@@ -356,7 +358,7 @@
public boolean canCloseUI(TuttiScreen nextScreen) {
boolean result = true;
if (getModel().isModify()) {
- int answer = askSaveBeforeLeaving(ui);
+ int answer = askSaveBeforeLeaving(_("tutti.dialog.askSaveBeforeLeaving.saveProtocol"));
result = answer == JOptionPane.NO_OPTION;
if (answer == JOptionPane.YES_OPTION) {
ActionEvent event = new ActionEvent(nextScreen, nextScreen.ordinal(), null);
Modified: trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties
===================================================================
--- trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-02-12 18:38:26 UTC (rev 406)
+++ trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-02-12 18:40:17 UTC (rev 407)
@@ -143,9 +143,16 @@
tutti.config.category.shortcuts.description=Liste des raccourcis clavier
tutti.config.category.ui=Interface utilisateur
tutti.config.category.ui.description=Options de l'interface utilisateur
-tutti.dialog.askSaveBeforeLeaving.createFishingOperation=Vous avez fait des modifications qu vous n'avez pas enregistrées. Voulez-vous les enregistrer ?
-tutti.dialog.askSaveBeforeLeaving.message=Vous avez fait des modifications qu vous n'avez pas enregistrées. Voulez-vous les enregistrer ?
-tutti.dialog.askSaveBeforeLeaving.saveFishingOperation=Vous avez fait des modifications qu vous n'avez pas enregistrées. Voulez-vous les enregistrer ?
+tutti.dialog.askCancelEditBeforeLeaving.cancelEditCatchBatch=La capture modifiée n'est pas valide. Voulez-vous annuler les modifications ?
+tutti.dialog.askCancelEditBeforeLeaving.cancelEditFishingOperation=Le trait modifié n'est pas valide. Voulez-vous annuler les modifications ?
+tutti.dialog.askCancelEditBeforeLeaving.title=Modifications non enregistrées mais invalides
+tutti.dialog.askSaveBeforeLeaving.createFishingOperation=Le trait n'a pas été créé. Voulez-vous l'enregistrer ?
+tutti.dialog.askSaveBeforeLeaving.message=Vous avez fait des modifications que vous n'avez pas enregistrées. Voulez-vous les enregistrer ?
+tutti.dialog.askSaveBeforeLeaving.saveCatchBatch=La capture a été modifiée. Voulez-vous enregistrer les modifications ?
+tutti.dialog.askSaveBeforeLeaving.saveProgram=La série de campagne a été modifiée. Voulez-vous enregistrer les modifications ?
+tutti.dialog.askSaveBeforeLeaving.saveCruise=La campagne a été modifiée. Voulez-vous enregistrer les modifications ?
+tutti.dialog.askSaveBeforeLeaving.saveProtocol=Le protocol a été modifié. Voulez-vous enregistrer les modifications ?
+tutti.dialog.askSaveBeforeLeaving.saveFishingOperation=Le trait a été modifié. Voulez-vous enregistrer les modifications ?
tutti.dialog.askSaveBeforeLeaving.title=Modifications non enregistrées
tutti.dialog.catches.species.computeWeight.error.message=Erreur lors de l'élévation des poids
tutti.dialog.catches.species.computeWeight.error.title=Erreur
@@ -273,6 +280,8 @@
tutti.label.tab.fishingOperation=Trait
tutti.label.tab.fishingOperation.general=Trait
tutti.label.tab.fishingOperation.hydrology=Paramètres hydrologiques
+tutti.label.tab.fishingOperation.environment=Environnement
+tutti.label.tab.fishingOperation.gearShooting=Mise en oeuvre de l'engin
tutti.label.tab.macroDechet=Macro déchets
tutti.label.tab.observationIndividuel=Observations individuelles
tutti.label.tab.plancton=Plancton
1
0
r406 - in trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing: environment gearshooting hydrology
by tchemit@users.forge.codelutin.com 12 Feb '13
by tchemit@users.forge.codelutin.com 12 Feb '13
12 Feb '13
Author: tchemit
Date: 2013-02-12 19:38:26 +0100 (Tue, 12 Feb 2013)
New Revision: 406
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/406
Log:
fix i18n missing keys
Modified:
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/environment/EnvironmentTabUIModel.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/gearshooting/GearShootingTabUIModel.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/hydrology/HydrologyTabUIModel.java
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/environment/EnvironmentTabUIModel.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/environment/EnvironmentTabUIModel.java 2013-02-12 18:33:43 UTC (rev 405)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/environment/EnvironmentTabUIModel.java 2013-02-12 18:38:26 UTC (rev 406)
@@ -26,6 +26,8 @@
import fr.ifremer.tutti.ui.swing.content.operation.fishing.CaracteristicTabUIModel;
+import static org.nuiton.i18n.I18n.n_;
+
/**
* @author kmorin
* @since 0.3
@@ -34,7 +36,8 @@
private static final long serialVersionUID = 1L;
- public static final String TITLE = "tutti.label.tab.fishingOperation.environment";
+ public static final String TITLE =
+ n_("tutti.label.tab.fishingOperation.environment");
@Override
public String getTitle() {
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/gearshooting/GearShootingTabUIModel.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/gearshooting/GearShootingTabUIModel.java 2013-02-12 18:33:43 UTC (rev 405)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/gearshooting/GearShootingTabUIModel.java 2013-02-12 18:38:26 UTC (rev 406)
@@ -25,10 +25,10 @@
*/
import fr.ifremer.tutti.ui.swing.content.operation.fishing.CaracteristicTabUIModel;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import static org.nuiton.i18n.I18n.n_;
+
/**
* @author kmorin
* @since 0.3
@@ -37,10 +37,9 @@
private static final long serialVersionUID = 1L;
- private static final Log log = LogFactory.getLog(GearShootingTabUIModel.class);
+ public static final String TITLE =
+ n_("tutti.label.tab.fishingOperation.gearShooting");
- public static final String TITLE = "tutti.label.tab.fishingOperation.gearShooting";
-
@Override
public String getTitle() {
return TITLE;
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/hydrology/HydrologyTabUIModel.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/hydrology/HydrologyTabUIModel.java 2013-02-12 18:33:43 UTC (rev 405)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/hydrology/HydrologyTabUIModel.java 2013-02-12 18:38:26 UTC (rev 406)
@@ -37,7 +37,8 @@
private static final long serialVersionUID = 1L;
- public static final String TITLE = n_("tutti.label.tab.fishingOperation.hydrology");
+ public static final String TITLE =
+ n_("tutti.label.tab.fishingOperation.hydrology");
@Override
public String getTitle() {
1
0