r693 - 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/batch test/java/fr/ifremer/tutti/persistence/service test/resources
Author: tchemit Date: 2013-03-27 22:49:05 +0100 (Wed, 27 Mar 2013) New Revision: 693 Url: http://forge.codelutin.com/projects/tutti/repository/revisions/693 Log: - fixes #2161: [ESPECES] affichage d'un nombre d'individus sur un lot p?\195?\168re avec des fils - ajout de m?\195?\169thodes pour manipuler les id en tant que Integer - resplit des service comme au d?\195?\169but : CatchBatchPS, SpeciesBatchPS, BenthosBatchPS (c'est plus simple) - nettoyage du code de persistence Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceService.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceImpl.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceService.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.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/SpeciesBatchPersistenceServiceImpl.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/batch/BatchPersistenceHelper.java trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceReadTest.java trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceWriteTest.java trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceReadTest.java trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceWriteTest.java trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceReadTest.java trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceWriteTest.java Removed: 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 Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceImpl.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/AbstractTuttiEntity.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/batch/ScientificCruiseCatchBatchValidator.java trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceWriteTest.java trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceWriteTest.java trunk/tutti-persistence/src/test/resources/log4j.properties Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceImpl.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceImpl.java 2013-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceImpl.java 2013-03-27 21:49:05 UTC (rev 693) @@ -49,7 +49,8 @@ import fr.ifremer.tutti.persistence.entities.referential.Vessel; import fr.ifremer.tutti.persistence.service.AccidentalBatchPersistenceService; import fr.ifremer.tutti.persistence.service.AttachmentPersistenceService; -import fr.ifremer.tutti.persistence.service.BatchPersistenceService; +import fr.ifremer.tutti.persistence.service.CatchBatchPersistenceService; +import fr.ifremer.tutti.persistence.service.BenthosBatchPersistenceService; import fr.ifremer.tutti.persistence.service.CruisePersistenceService; import fr.ifremer.tutti.persistence.service.FishingOperationPersistenceService; import fr.ifremer.tutti.persistence.service.MacroWasteBatchPersistenceService; @@ -57,6 +58,7 @@ import fr.ifremer.tutti.persistence.service.ProgramPersistenceService; import fr.ifremer.tutti.persistence.service.ProtocolPersistenceService; import fr.ifremer.tutti.persistence.service.ReferentialPersistenceService; +import fr.ifremer.tutti.persistence.service.SpeciesBatchPersistenceService; import fr.ifremer.tutti.persistence.service.TuttiPersistenceServiceLocator; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; @@ -91,9 +93,15 @@ protected FishingOperationPersistenceService fishingOperationService; @Autowired - protected BatchPersistenceService batchService; + protected CatchBatchPersistenceService catchBatchService; @Autowired + protected SpeciesBatchPersistenceService speciesBatchService; + + @Autowired + protected BenthosBatchPersistenceService benthosBatchService; + + @Autowired protected PlanktonBatchPersistenceService planktonBatchService; @Autowired @@ -130,7 +138,9 @@ programService.init(); cruiseService.init(); fishingOperationService.init(); - batchService.init(); + catchBatchService.init(); + speciesBatchService.init(); + benthosBatchService.init(); planktonBatchService.init(); macroWasteBatchService.init(); accidentalBatchService.init(); @@ -148,7 +158,9 @@ programService.close(); cruiseService.close(); fishingOperationService.close(); - batchService.close(); + catchBatchService.close(); + speciesBatchService.close(); + benthosBatchService.close(); planktonBatchService.close(); macroWasteBatchService.close(); accidentalBatchService.close(); @@ -506,7 +518,7 @@ @Override public CatchBatch getCatchBatchFromFishingOperation(String id) throws InvalidBatchModelException { try { - return batchService.getCatchBatchFromFishingOperation(id); + return catchBatchService.getCatchBatchFromFishingOperation(id); } catch (CatchBatchValidationException e) { throw new InvalidBatchModelException( "L'arbre d'échantillonage n'est pas compatible avec celui de Tutti.", e); @@ -515,12 +527,12 @@ @Override public CatchBatch createCatchBatch(CatchBatch bean) { - return batchService.createCatchBatch(bean); + return catchBatchService.createCatchBatch(bean); } @Override public CatchBatch saveCatchBatch(CatchBatch bean) { - return batchService.saveCatchBatch(bean); + return catchBatchService.saveCatchBatch(bean); } //------------------------------------------------------------------------// @@ -529,42 +541,42 @@ @Override public BatchContainer<SpeciesBatch> getRootSpeciesBatch(String fishingOperationId) { - return batchService.getRootSpeciesBatch(fishingOperationId); + return speciesBatchService.getRootSpeciesBatch(fishingOperationId); } @Override public SpeciesBatch createSpeciesBatch(SpeciesBatch bean, String parentBatchId) { - return batchService.createSpeciesBatch(bean, parentBatchId); + return speciesBatchService.createSpeciesBatch(bean, parentBatchId); } @Override public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) { - return batchService.saveSpeciesBatch(bean); + return speciesBatchService.saveSpeciesBatch(bean); } @Override public void deleteSpeciesBatch(String id) { - batchService.deleteSpeciesBatch(id); + speciesBatchService.deleteSpeciesBatch(id); } @Override public void deleteSpeciesSubBatch(String id) { - batchService.deleteSpeciesSubBatch(id); + speciesBatchService.deleteSpeciesSubBatch(id); } @Override public void changeSpeciesBatchSpecies(String batchId, Species species) { - batchService.changeSpeciesBatchSpecies(batchId, species); + speciesBatchService.changeSpeciesBatchSpecies(batchId, species); } @Override public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(String speciesBatchId) { - return batchService.getAllSpeciesBatchFrequency(speciesBatchId); + return speciesBatchService.getAllSpeciesBatchFrequency(speciesBatchId); } @Override public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(String speciesBatchId, List<SpeciesBatchFrequency> frequencies) { - return batchService.saveSpeciesBatchFrequency(speciesBatchId, frequencies); + return speciesBatchService.saveSpeciesBatchFrequency(speciesBatchId, frequencies); } //------------------------------------------------------------------------// @@ -573,43 +585,43 @@ @Override public BatchContainer<SpeciesBatch> getRootBenthosBatch(String fishingOperationId) { - return batchService.getRootBenthosBatch(fishingOperationId); + return benthosBatchService.getRootBenthosBatch(fishingOperationId); } @Override public SpeciesBatch createBenthosBatch(SpeciesBatch bean, String parentBatchId) { - return batchService.createBenthosBatch(bean, parentBatchId); + return benthosBatchService.createBenthosBatch(bean, parentBatchId); } @Override public SpeciesBatch saveBenthosBatch(SpeciesBatch bean) { - return batchService.saveBenthosBatch(bean); + return benthosBatchService.saveBenthosBatch(bean); } @Override public void deleteBenthosBatch(String id) { - batchService.deleteBenthosBatch(id); + benthosBatchService.deleteBenthosBatch(id); } @Override public void deleteBenthosSubBatch(String id) { - batchService.deleteBenthosSubBatch(id); + benthosBatchService.deleteBenthosSubBatch(id); } @Override public void changeBenthosBatchSpecies(String batchId, Species species) { - batchService.changeBenthosBatchSpecies(batchId, species); + benthosBatchService.changeBenthosBatchSpecies(batchId, species); } @Override public List<SpeciesBatchFrequency> getAllBenthosBatchFrequency(String benthosBatchId) { - return batchService.getAllBenthosBatchFrequency(benthosBatchId); + return benthosBatchService.getAllBenthosBatchFrequency(benthosBatchId); } @Override public List<SpeciesBatchFrequency> saveBenthosBatchFrequency(String benthosBatchId, List<SpeciesBatchFrequency> frequencies) { - return batchService.saveBenthosBatchFrequency(benthosBatchId, frequencies); + return benthosBatchService.saveBenthosBatchFrequency(benthosBatchId, frequencies); } //------------------------------------------------------------------------// Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/AbstractTuttiEntity.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/AbstractTuttiEntity.java 2013-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/AbstractTuttiEntity.java 2013-03-27 21:49:05 UTC (rev 693) @@ -45,6 +45,8 @@ protected String id; + protected Integer intId; + @Override public String getId() { return id; @@ -53,8 +55,21 @@ @Override public void setId(String id) { this.id = id; + intId = null; } + public void setId(Integer id) { + intId = id; + this.id = id == null ? null : String.valueOf(id); + } + + public Integer getIdAsInt() { + if (intId == null && id != null) { + intId = Integer.valueOf(id); + } + return intId; + } + protected <B> B getChild(Collection<B> child, int index) { return CollectionUtil.getOrNull(child, index); } Deleted: 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-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java 2013-03-27 21:49:05 UTC (rev 693) @@ -1,208 +0,0 @@ -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 fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException; -import fr.ifremer.tutti.persistence.TuttiPersistenceServiceImplementor; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -import fr.ifremer.tutti.persistence.entities.data.CatchBatch; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; -import fr.ifremer.tutti.persistence.entities.referential.Species; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Transactional(readOnly = true) -public interface BatchPersistenceService extends TuttiPersistenceServiceImplementor { - - //------------------------------------------------------------------------// - //-- CatchBatch methods --// - //------------------------------------------------------------------------// - - /** - * Get the catchBatch from the fishing Operation id. - * - * @param fishingOperationId id of the fihsing operation - * @return found catchBatch - * @throws CatchBatchValidationException - */ - CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) throws CatchBatchValidationException; - - /** - * Create the given CatchBatch and return it. - * - * @param bean catchBatch to create - * @return created catchBatch - */ - @Transactional(readOnly = false) - CatchBatch createCatchBatch(CatchBatch bean); - - /** - * Save the given catchBatch and return it. - * - * @param bean batch to save - * @return the saved catchBatch - */ - @Transactional(readOnly = false) - CatchBatch saveCatchBatch(CatchBatch bean); - - //------------------------------------------------------------------------// - //-- SpeciesBatch methods --// - //------------------------------------------------------------------------// - - /** - * Get the batch parent of 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.2 - */ - BatchContainer<SpeciesBatch> getRootSpeciesBatch(String fishingOperationId); - - @Transactional(readOnly = false) - SpeciesBatch createSpeciesBatch(SpeciesBatch bean, String parentBatchId); - - @Transactional(readOnly = false) - SpeciesBatch saveSpeciesBatch(SpeciesBatch bean); - - @Transactional(readOnly = false) - void deleteSpeciesBatch(String id); - - @Transactional(readOnly = false) - void deleteSpeciesSubBatch(String id); - - /** - * Change the species in the given {@code batchId} and in all his - * sub batches. - * - * @param batchId id of the root species batch to treat - * @param species species to affect to all batches - */ - @Transactional(readOnly = false) - void changeSpeciesBatchSpecies(String batchId, Species species); - - //------------------------------------------------------------------------// - //-- SpeciesBatchFrequency methods (for species) --// - //------------------------------------------------------------------------// - - /** - * 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); - - - //------------------------------------------------------------------------// - //-- Benthos 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 - */ - BatchContainer<SpeciesBatch> getRootBenthosBatch(String fishingOperationId); - - @Transactional(readOnly = false) - SpeciesBatch createBenthosBatch(SpeciesBatch bean, String parentBatchId); - - @Transactional(readOnly = false) - SpeciesBatch saveBenthosBatch(SpeciesBatch bean); - - @Transactional(readOnly = false) - void deleteBenthosBatch(String id); - - @Transactional(readOnly = false) - void deleteBenthosSubBatch(String id); - - /** - * Change the species in the given {@code batchId} and in all his - * sub batches. - * - * @param batchId id of the root Benthos batch to treat - * @param species species to affect to all batches - */ - @Transactional(readOnly = false) - void changeBenthosBatchSpecies(String batchId, Species species); - - //------------------------------------------------------------------------// - //-- SpeciesBatchFrequency methods (for benthos) --// - //------------------------------------------------------------------------// - - /** - * Get all frequencies for the given species batch. - * - * @param benthosBatchId the id of the species batch to seek. - * @return the list of frequencies for the given benthos batch id - * @since 1.0 - */ - List<SpeciesBatchFrequency> getAllBenthosBatchFrequency(String benthosBatchId); - - /** - * Save all given {@link SpeciesBatchFrequency} into the given - * {@code benthosBatchId}. If some are not existing then creates them. - * <p/> - * <strong>Note:</strong> This will as a side effect remove all previous - * frequency for this benthos batch. - * - * @param benthosBatchId 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> saveBenthosBatchFrequency(String benthosBatchId, - List<SpeciesBatchFrequency> frequencies); - - -} \ No newline at end of file Deleted: 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-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java 2013-03-27 21:49:05 UTC (rev 693) @@ -1,1630 +0,0 @@ -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 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.validator.CatchBatchValidationException; -import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidator; -import fr.ifremer.adagio.core.dao.data.measure.Measurement; -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.pmfm.QualitativeValue; -import fr.ifremer.adagio.core.dao.referential.pmfm.QualitativeValueImpl; -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.BatchContainer; -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 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.io.Serializable; -import java.text.MessageFormat; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -@Service("batchPersistenceService") -public class BatchPersistenceServiceImpl - extends AbstractPersistenceService implements BatchPersistenceService { - - /** Logger. */ - private static final Log log = - LogFactory.getLog(BatchPersistenceServiceImpl.class); - - @Resource(name = "referentialPersistenceService") - protected ReferentialPersistenceService referentialService; - - @Resource(name = "catchBatchDao") - protected CatchBatchExtendDao catchBatchDao; - - @Resource(name = "scientificCruiseCatchBatchValidator") - protected CatchBatchValidator catchBatchValidator; - - @Override - public void init() { - super.init(); - catchBatchDao.registerCatchBatchValidator(catchBatchValidator); - } - - @Override - public void close() { - catchBatchDao.unregisterCatchBatchValidator(catchBatchValidator); - super.close(); - } - - //------------------------------------------------------------------------// - //-- CatchBatch methods --// - //------------------------------------------------------------------------// - - @Override - public CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) throws CatchBatchValidationException { - Preconditions.checkNotNull(fishingOperationId); - - Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId)); - - fr.ifremer.adagio.core.dao.data.batch.CatchBatch source; - // wenever want to repair anything from Tutti - source = catchBatchDao.loadFullTree(catchBatchId, true, false); - - 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); - if (inertBatch != null) { - result.setSpeciesTotalInertWeight(inertBatch.getWeight()); - } - - // Alive no itemized - SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), - "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE); - if (livingNotItemizedBatch != null) { - result.setSpeciesTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight()); - } - } - - // Benthos - SortingBatch benthosBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(), - "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); - if (benthosBatch != null) { - result.setBenthosTotalSampleSortedWeight(benthosBatch.getWeight()); - result.setBenthosTotalSortedWeight(benthosBatch.getWeightBeforeSampling()); - } - - // TODO : Plancton... - } - - // Hors Vrac - SortingBatch horsVracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(), - "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID); - if (horsVracBatch != null) { - result.setCatchTotalUnsortedWeight(horsVracBatch.getWeight()); - { - // Species - SortingBatch speciesBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(), - "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); - if (speciesBatch != null) { - result.setSpeciesTotalUnsortedWeight(speciesBatch.getWeight()); - } - - SortingBatch benthosBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(), - "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); - if (benthosBatch != null) { - result.setBenthosTotalUnsortedWeight(benthosBatch.getWeight()); - } - - // TODO : Plancton... - } - } - - // Non trié - SortingBatch unsortedBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(), - "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID); - if (unsortedBatch != null) { - 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 - 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; - } - - //------------------------------------------------------------------------// - //-- SpeciesBatch methods --// - //------------------------------------------------------------------------// - - @Override - public BatchContainer<SpeciesBatch> getRootSpeciesBatch(String fishingOperationId) { - - // Load batch tree - Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId)); - fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); - - // 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); - - // container of speciesBatch is arbitraty put on vrac type (there is - // no common ancestor for all species batch). - BatchContainer<SpeciesBatch> result = new BatchContainer<SpeciesBatch>(); - result.setId(String.valueOf(vracSpeciesBatch.getId())); - - for (Batch batch1 : vracSpeciesBatch.getChildBatchs()) { - SortingBatch source = (SortingBatch) batch1; - - // evict some special batches : Life (or Biota) and Inert - if (source.getReferenceTaxon() != null - && !enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) - && !enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId())) { - SpeciesBatch target = new SpeciesBatch(); - - entityToBean(source, target); - result.addChildren(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); - if (horsVracSpeciesBatch != null) { - for (Batch batch : horsVracSpeciesBatch.getChildBatchs()) { - SortingBatch source = (SortingBatch) batch; - - SpeciesBatch target = new SpeciesBatch(); - - entityToBean(source, target); - result.addChildren(target); - } - } - - 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()); - - 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(); - speciesBatchToEntity(bean, batch, parentBatchId, catchBatch); - batch = catchBatchDao.createSortingBatch(batch, catchBatch); - - 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(); - } - speciesBatchToEntity(bean, batch, parentBatchId, catchBatch); - catchBatchDao.updateSortingBatch(batch, catchBatch); - getCurrentSession().flush(); - - return bean; - } - - @Override - public void deleteSpeciesBatch(String id) { - Preconditions.checkNotNull(id); - - getCurrentSession().setFlushMode(FlushMode.COMMIT); - - catchBatchDao.removeWithChildren(Integer.valueOf(id)); - - 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()); - - catchBatchDao.setSortingBatchReferenceTaxon(batchId, species.getReferenceTaxonId()); - } - - //------------------------------------------------------------------------// - //-- SpeciesBatchFrequency methods --// - //------------------------------------------------------------------------// - - @Override - 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 (Batch batch : sortingBatch.getChildBatchs()) { - SortingBatch source = (SortingBatch) batch; - SpeciesBatchFrequency target = new SpeciesBatchFrequency(); - - entityToBean(source, target); - results.add(target); - } - return Collections.unmodifiableList(results); - } - - @Override - public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency( - String speciesBatchId, - List<SpeciesBatchFrequency> frequencies) { - Preconditions.checkNotNull(speciesBatchId); - Preconditions.checkNotNull(frequencies); - - List<SpeciesBatchFrequency> notNullFrequencies = Lists.newArrayList(); - - // Check that all frequencies have the same length PMFM (before doing any db call) - // and remove null frequencies - String pmfmId = null; - for (SpeciesBatchFrequency source : frequencies) { - - if (source.getLengthStepCaracteristic() != null) { - if (pmfmId == null) { - pmfmId = source.getLengthStepCaracteristic().getId(); - } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) { - throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic"); - } - notNullFrequencies.add(source); - } - } - - 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 notNullFrequencies; - } - - // 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 (Batch batch : parentBatch.getChildBatchs()) { - SortingBatch sortingBatch = (SortingBatch) batch; - notUpdatedChildIds.add(sortingBatch.getId()); - } - - short rankOrder = 0; - List<SortingBatch> batchsToUpdate = Lists.newArrayList(); - for (SpeciesBatchFrequency source : notNullFrequencies) { - rankOrder++; - - // Not existing batch - SortingBatch target; - 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 - catchBatchDao.createSortingBatch(target, catchBatch); - source.setId(target.getId().toString()); - } - - // Existing batch - else { - target = catchBatchDao.loadSortingBatch(Integer.valueOf(source.getId()), catchBatch); - - // 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) { - catchBatchDao.updateSortingBatch(batchsToUpdate, catchBatch); - } - - if (notUpdatedChildIds.size() > 0) { - for (Integer batchId : notUpdatedChildIds) { - catchBatchDao.removeWithChildren(batchId, catchBatch); - } - } - - getCurrentSession().flush(); - - return Collections.unmodifiableList(notNullFrequencies); - } - - //------------------------------------------------------------------------// - //-- Benthos Batch methods --// - //------------------------------------------------------------------------// - - @Override - public BatchContainer<SpeciesBatch> getRootBenthosBatch(String fishingOperationId) { - // Load batch tree - Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId)); - fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); - - // Vrac / Benthos - 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_BENTHOS); - - BatchContainer<SpeciesBatch> result = new BatchContainer<SpeciesBatch>(); - result.setId(String.valueOf(vracSpeciesBatch.getId())); - for (Batch batch1 : vracSpeciesBatch.getChildBatchs()) { - SortingBatch source = (SortingBatch) batch1; - - // evict some special batches : Life (or Biota) and Inert - if (source.getReferenceTaxon() != null - && !enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) - && !enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId())) { - SpeciesBatch target = new SpeciesBatch(); - - entityToBean(source, target); - result.addChildren(target); - } - } - - // Hors-Vrac / Benthos - 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_BENTHOS); - if (horsVracSpeciesBatch != null) { - for (Batch batch : horsVracSpeciesBatch.getChildBatchs()) { - SortingBatch source = (SortingBatch) batch; - - SpeciesBatch target = new SpeciesBatch(); - - entityToBean(source, target); - result.addChildren(target); - } - } - return result; - } - - @Override - public SpeciesBatch createBenthosBatch(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(); - benthosBatchToEntity(bean, batch, parentBatchId, catchBatch); - batch = catchBatchDao.createSortingBatch(batch, catchBatch); - - bean.setId(String.valueOf(batch.getId())); - - getCurrentSession().flush(); - - return bean; - } - - @Override - public SpeciesBatch saveBenthosBatch(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(); - } - benthosBatchToEntity(bean, batch, parentBatchId, catchBatch); - catchBatchDao.updateSortingBatch(batch, catchBatch); - getCurrentSession().flush(); - - return bean; - } - - @Override - public void deleteBenthosBatch(String id) { - Preconditions.checkNotNull(id); - - getCurrentSession().setFlushMode(FlushMode.COMMIT); - - catchBatchDao.removeWithChildren(Integer.valueOf(id)); - - getCurrentSession().flush(); - } - - @Override - public void deleteBenthosSubBatch(String id) { - deleteBenthosBatch(id); - } - - @Override - public void changeBenthosBatchSpecies(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."); - } - - //------------------------------------------------------------------------// - //-- SpeciesBatchFrequency methods (for benthos) --// - //------------------------------------------------------------------------// - - @Override - public List<SpeciesBatchFrequency> getAllBenthosBatchFrequency(String benthosBatchId) { - List<SpeciesBatchFrequency> results = Lists.newArrayList(); - - Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(benthosBatchId)); - fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); - - if (catchBatchId == null) { - return results; - } - - SortingBatch sortingBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(benthosBatchId)); - - for (Batch batch : sortingBatch.getChildBatchs()) { - SortingBatch source = (SortingBatch) batch; - SpeciesBatchFrequency target = new SpeciesBatchFrequency(); - - entityToBean(source, target); - results.add(target); - } - return Collections.unmodifiableList(results); - } - - @Override - public List<SpeciesBatchFrequency> saveBenthosBatchFrequency(String benthosBatchId, - List<SpeciesBatchFrequency> frequencies) { - Preconditions.checkNotNull(benthosBatchId); - Preconditions.checkNotNull(frequencies); - - // Check that all frequencies have the same length PMFM (before doing any db call) - String pmfmId = null; - for (SpeciesBatchFrequency source : frequencies) { - - if (pmfmId == null) { - pmfmId = source.getLengthStepCaracteristic().getId(); - } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) { - throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic"); - } - } - - getCurrentSession().setFlushMode(FlushMode.COMMIT); - - Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(benthosBatchId)); - 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(benthosBatchId)); - - // Remember child ids, to remove unchanged item (see at bottom in this method) - List<Integer> notUpdatedChildIds = Lists.newArrayList(); - for (Batch batch : parentBatch.getChildBatchs()) { - SortingBatch sortingBatch = (SortingBatch) batch; - notUpdatedChildIds.add(sortingBatch.getId()); - } - - short rankOrder = 0; - List<SortingBatch> batchsToUpdate = Lists.newArrayList(); - for (SpeciesBatchFrequency source : frequencies) { - rankOrder++; - - // Not existing batch - SortingBatch target; - 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 - catchBatchDao.createSortingBatch(target, catchBatch); - source.setId(target.getId().toString()); - } - - // Existing batch - else { - target = catchBatchDao.getSortingBatchById(catchBatch, 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) { - catchBatchDao.updateSortingBatch(batchsToUpdate, catchBatch); - } - - if (notUpdatedChildIds.size() > 0) { - for (Integer batchId : notUpdatedChildIds) { - catchBatchDao.removeWithChildren(batchId, catchBatch); - } - } - - getCurrentSession().flush(); - - return Collections.unmodifiableList(frequencies); - } - - - //------------------------------------------------------------------------// - //-- Internal methods --// - //------------------------------------------------------------------------// - - 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 = catchBatchDao.getInheritedSortingMeasurement(source, enumeration.PMFM_ID_SORTED_UNSORTED); - } - if (sm != null) { - SampleCategoryEnum sampleCategory = enumeration.getSampleCategoryByPmfmId(sm.getPmfm().getId()); - if (sampleCategory != null) { - Integer qualitativeId = null; - if (sm.getQualitativeValue() != null) { - qualitativeId = sm.getQualitativeValue().getId(); - } - setSampleCategoryQualitative(target, sm.getPmfm().getId(), sm.getNumericalValue(), sm.getAlphanumericalValue(), qualitativeId); - } - } - - // 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 (Batch batch : source.getChildBatchs()) { - SortingBatch sourceChild = (SortingBatch) batch; - SpeciesBatch targetChild = new SpeciesBatch(); - entityToBean(sourceChild, targetChild); - if (targetChild.getSampleCategoryValue() != null) { - targetChilds.add(targetChild); - targetChild.setParentBatch(target); - } - } - target.setChildBatchs(targetChilds); - } - - return target; - } - - 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()); - } - } - - protected void speciesBatchToEntity(SpeciesBatch source, - SortingBatch target, - String parentBatchId, - fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) { - sortingBatchToEntity(source, target, parentBatchId, catchBatch, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); - } - - protected void benthosBatchToEntity(SpeciesBatch source, - SortingBatch target, - String parentBatchId, - fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) { - sortingBatchToEntity(source, target, parentBatchId, catchBatch, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); - } - - protected void sortingBatchToEntity(SpeciesBatch source, - SortingBatch target, - String parentBatchId, - fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch, - Integer batchPmfm) { - - 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, batchPmfm); - } - - // 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) { - rankOrder += (short) source.getParentBatch().getChildBatchs().size(); - } else if (target.getParentBatch() != null && target.getParentBatch().getChildBatchs() != null) { - rankOrder += (short) target.getParentBatch().getChildBatchs().size(); - } - target.setRankOrder(rankOrder); - } - - // Force subgroup count to '1', as Allegro - target.setSubgroupCount(1f); - - // Weight or SampleCategoryWeight - if (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 = catchBatchDao.setQuantificationMeasurement(target, - enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true); - notChangedQuantificationMeasurements.remove(quantificationMeasurement); - } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) { - QuantificationMeasurement quantificationMeasurement = catchBatchDao.setQuantificationMeasurement(target, - enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true); - notChangedQuantificationMeasurements.remove(quantificationMeasurement); - } - - // Sampling Ratio - if (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 = catchBatchDao.setQuantificationMeasurement(target, - enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true); - notChangedQuantificationMeasurements.remove(quantificationMeasurement); - } - - // Sorting measurement - if (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 = 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 = setSortingMeasurement(target, recorderDepartmentId, - source.getSampleCategoryType(), source.getSampleCategoryValue()); - notChangedSortingMeasurements.remove(sortingMeasurement); - } - } - - // Individual count - if (source.getNumber() == null) { - target.setIndividualCount(null); - } else if (source.getNumber() != null) { - target.setIndividualCount(source.getNumber()); - } - - // Species - if (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 (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 void setBatchParents(SpeciesBatch source, - SortingBatch target, - String parentBatchIdStr, - fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch, - Integer batchPmfmId) { - - Preconditions.checkNotNull(target); - Preconditions.checkNotNull(source.getFishingOperation()); - Preconditions.checkNotNull(source.getFishingOperation().getId()); - - // Load existing parent and root - SortingBatch parentBatch; - if (parentBatchIdStr != null) { - parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(parentBatchIdStr)); - } - - // Or retrieve parent batch, from pmfm id - else { - // Retrieve category type - Integer pmfmId = 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, batchPmfmId); - - // 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); - } - - protected 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 = enumeration.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 = catchBatchDao.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 = 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 = catchBatchDao.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); - } - - // ----------------------------------------------------------------------------- - // Sorted Vrac > Benthos - // ----------------------------------------------------------------------------- - { - SortingBatch benthosBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); - if (benthosBatch == null) { - benthosBatch = SortingBatch.Factory.newInstance(); - batch.getChildBatchs().add(benthosBatch); - } - beanToEntitySortingBatch(target, batch, benthosBatch, recorderDepartmentId, - enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS, - source.getBenthosTotalSampleSortedWeight(), source.getBenthosTotalSortedWeight(), - copyIfNull); - benthosBatch.setRankOrder((short) 2); - } - - // TODO 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); - - // ----------------------------------------------------------------------------- - // Hors 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.getSpeciesTotalUnsortedWeight(), null, - copyIfNull); - speciesBatch.setRankOrder((short) 1); - } - - // ----------------------------------------------------------------------------- - // Hors Vrac > Benthos : - // ----------------------------------------------------------------------------- - { - SortingBatch benthosBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); - if (benthosBatch == null) { - benthosBatch = SortingBatch.Factory.newInstance(); - batch.getChildBatchs().add(benthosBatch); - } - beanToEntitySortingBatch(target, batch, benthosBatch, recorderDepartmentId, - enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS, - source.getBenthosTotalUnsortedWeight(), null, - copyIfNull); - benthosBatch.setRankOrder((short) 2); - } - - // TODO : 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 = catchBatchDao.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 = 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 = catchBatchDao.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 = catchBatchDao.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; - } - - protected void setMeasurement(Measurement measurement, Caracteristic caracteristic, Serializable value) { - if (caracteristic.getCaracteristicType() == CaracteristicType.TEXT) { - measurement.setAlphanumericalValue((String) value); - } else if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER) { - measurement.setNumericalValue((Float) value); - } else if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { - Integer qvId; - if (value instanceof CaracteristicQualitativeValue) { - qvId = Integer.valueOf(((CaracteristicQualitativeValue) value).getId()); - } else if (value instanceof Integer) { - qvId = (Integer) value; - } - // TODO BL : not used ? => to remove - else { - qvId = Integer.valueOf(value.toString()); - } - QualitativeValue qv = load(QualitativeValueImpl.class, qvId); - measurement.setQualitativeValue(qv); - } - } - - protected SortingMeasurement setSortingMeasurement( - SortingBatch sortingBatch, Integer recorderDepartmentId, - SampleCategoryEnum sampleCategory, Serializable value) { - Preconditions.checkNotNull(sampleCategory); - Preconditions.checkNotNull(value); - - Integer pmfmId = sampleCategory2PmfmId(sampleCategory); - - Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId); - SortingMeasurement sortingMeasurement = catchBatchDao.getSortingMeasurement( - sortingBatch, pmfmId, recorderDepartmentId, true); - setMeasurement(sortingMeasurement, caracteristic, value); - return sortingMeasurement; - } - - protected SortingMeasurement setSortingMeasurement( - SortingBatch sortingBatch, Integer recorderDepartmentId, - Integer pmfmId, Serializable value) { - Preconditions.checkNotNull(pmfmId); - Preconditions.checkNotNull(value); - - Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId); - SortingMeasurement sortingMeasurement = catchBatchDao.getSortingMeasurement( - sortingBatch, pmfmId, recorderDepartmentId, true); - setMeasurement(sortingMeasurement, caracteristic, value); - return sortingMeasurement; - } - - protected Integer sampleCategory2PmfmId(SampleCategoryEnum sampleCategory) { - Integer pmfmId = null; - if (sampleCategory == SampleCategoryEnum.sortedUnsorted) { - pmfmId = enumeration.PMFM_ID_SORTED_UNSORTED; - } else if (sampleCategory == SampleCategoryEnum.size) { - pmfmId = enumeration.PMFM_ID_SIZE_CATEGORY; - } else if (sampleCategory == SampleCategoryEnum.maturity) { - pmfmId = enumeration.PMFM_ID_MATURITY; - } else if (sampleCategory == SampleCategoryEnum.sex) { - pmfmId = enumeration.PMFM_ID_SEX; - } else if (sampleCategory == SampleCategoryEnum.age) { - pmfmId = enumeration.PMFM_ID_AGE; - } - if (pmfmId == null) { - throw new IllegalArgumentException("Unable to find corresponding PMFM.ID for sampleCategory : " + sampleCategory.name()); - } - return pmfmId; - } - -} Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceService.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceService.java (rev 0) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceService.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,111 @@ +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 fr.ifremer.tutti.persistence.TuttiPersistenceServiceImplementor; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * Service to persist *benthos* {@link SpeciesBatch}. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.2 + */ +@Transactional(readOnly = true) +public interface BenthosBatchPersistenceService extends TuttiPersistenceServiceImplementor { + + //------------------------------------------------------------------------// + //-- Benthos 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 + */ + BatchContainer<SpeciesBatch> getRootBenthosBatch(String fishingOperationId); + + @Transactional(readOnly = false) + SpeciesBatch createBenthosBatch(SpeciesBatch bean, String parentBatchId); + + @Transactional(readOnly = false) + SpeciesBatch saveBenthosBatch(SpeciesBatch bean); + + @Transactional(readOnly = false) + void deleteBenthosBatch(String id); + + @Transactional(readOnly = false) + void deleteBenthosSubBatch(String id); + + /** + * Change the species in the given {@code batchId} and in all his + * sub batches. + * + * @param batchId id of the root Benthos batch to treat + * @param species species to affect to all batches + */ + @Transactional(readOnly = false) + void changeBenthosBatchSpecies(String batchId, Species species); + + //------------------------------------------------------------------------// + //-- SpeciesBatchFrequency methods (for benthos) --// + //------------------------------------------------------------------------// + + /** + * Get all frequencies for the given species batch. + * + * @param benthosBatchId the id of the species batch to seek. + * @return the list of frequencies for the given benthos batch id + * @since 1.0 + */ + List<SpeciesBatchFrequency> getAllBenthosBatchFrequency(String benthosBatchId); + + /** + * Save all given {@link SpeciesBatchFrequency} into the given + * {@code benthosBatchId}. If some are not existing then creates them. + * <p/> + * <strong>Note:</strong> This will as a side effect remove all previous + * frequency for this benthos batch. + * + * @param benthosBatchId 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> saveBenthosBatchFrequency(String benthosBatchId, + List<SpeciesBatchFrequency> frequencies); +} Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceService.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Added: svn:eol-style + native Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceImpl.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceImpl.java (rev 0) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceImpl.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,334 @@ +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 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.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import fr.ifremer.tutti.persistence.service.batch.BatchPersistenceHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.FlushMode; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * Default implementation of {@link BenthosBatchPersistenceService}. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.2 + */ +@Service("benthosBatchPersistenceService") +public class BenthosBatchPersistenceServiceImpl extends AbstractPersistenceService + implements BenthosBatchPersistenceService { + + /** Logger. */ + private static final Log log = + LogFactory.getLog(BenthosBatchPersistenceServiceImpl.class); + + @Resource(name = "referentialPersistenceService") + protected ReferentialPersistenceService referentialService; + + @Resource(name = "catchBatchDao") + protected CatchBatchExtendDao catchBatchDao; + + @Resource(name = "batchPersistenceHelper") + protected BatchPersistenceHelper batchHelper; + + //------------------------------------------------------------------------// + //-- Benthos Batch methods --// + //------------------------------------------------------------------------// + + @Override + public BatchContainer<SpeciesBatch> getRootBenthosBatch(String fishingOperationId) { + Preconditions.checkNotNull(fishingOperationId); + + // Load batch tree + Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId)); + Preconditions.checkNotNull(catchBatchId); + + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + Preconditions.checkNotNull(catchBatch); + + Collection<Batch> catchBatchChils = catchBatch.getChildBatchs(); + + // Vrac / Benthos + SortingBatch vracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatchChils, + "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID, + "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); + + BatchContainer<SpeciesBatch> result = new BatchContainer<SpeciesBatch>(); + result.setId(vracSpeciesBatch.getId()); + + for (Batch batch1 : vracSpeciesBatch.getChildBatchs()) { + SortingBatch source = (SortingBatch) batch1; + + // evict some special batches : Life (or Biota) and Inert + if (source.getReferenceTaxon() != null + && !enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) + && !enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId())) { + + SpeciesBatch target = new SpeciesBatch(); + batchHelper.entityToSpeciesBatch(source, target); + result.addChildren(target); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac > Benthos > " + target.getSpecies().getReferenceTaxonId() + " : " + target.getId()); + } + } + } + + // Hors-Vrac / Benthos + SortingBatch horsVracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatchChils, + "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID, + "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); + if (horsVracSpeciesBatch != null) { + for (Batch batch : horsVracSpeciesBatch.getChildBatchs()) { + + SpeciesBatch target = new SpeciesBatch(); + batchHelper.entityToSpeciesBatch((SortingBatch) batch, target); + result.addChildren(target); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Hors Vrac > Benthos > " + target.getSpecies().getReferenceTaxonId() + " : " + target.getId()); + } + } + } + return result; + } + + @Override + public SpeciesBatch createBenthosBatch(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(bean.getFishingOperation().getIdAsInt()); + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + + SortingBatch batch = SortingBatch.Factory.newInstance(); + benthosBatchToEntity(bean, batch, parentBatchId, catchBatch); + batch = catchBatchDao.createSortingBatch(batch, catchBatch); + + bean.setId(batch.getId()); + + getCurrentSession().flush(); + + return bean; + } + + @Override + public SpeciesBatch saveBenthosBatch(SpeciesBatch bean) { + Preconditions.checkNotNull(bean); + Preconditions.checkNotNull(bean.getId()); + + // Load batch tree + Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(bean.getIdAsInt()); + Preconditions.checkNotNull(catchBatchId); + + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + Preconditions.checkNotNull(catchBatch); + + getCurrentSession().setFlushMode(FlushMode.COMMIT); + + SortingBatch batch = catchBatchDao.getSortingBatchById(catchBatch, bean.getIdAsInt()); + String parentBatchId = null; + if (bean.getParentBatch() != null) { + parentBatchId = bean.getParentBatch().getId(); + } + benthosBatchToEntity(bean, batch, parentBatchId, catchBatch); + catchBatchDao.updateSortingBatch(batch, catchBatch); + getCurrentSession().flush(); + + return bean; + } + + @Override + public void deleteBenthosBatch(String id) { + Preconditions.checkNotNull(id); + + getCurrentSession().setFlushMode(FlushMode.COMMIT); + + catchBatchDao.removeWithChildren(Integer.valueOf(id)); + + getCurrentSession().flush(); + } + + @Override + public void deleteBenthosSubBatch(String id) { + Preconditions.checkNotNull(id); + deleteBenthosBatch(id); + } + + @Override + public void changeBenthosBatchSpecies(String batchId, Species species) { + + Preconditions.checkNotNull(batchId); + Preconditions.checkNotNull(species); + Preconditions.checkNotNull(species.getReferenceTaxonId()); + + catchBatchDao.setSortingBatchReferenceTaxon(batchId, species.getReferenceTaxonId()); + } + + //------------------------------------------------------------------------// + //-- SpeciesBatchFrequency methods (for benthos) --// + //------------------------------------------------------------------------// + + @Override + public List<SpeciesBatchFrequency> getAllBenthosBatchFrequency(String benthosBatchId) { + List<SpeciesBatchFrequency> results = Lists.newArrayList(); + + Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(benthosBatchId)); + if (catchBatchId == null) { + return results; + } + + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + + SortingBatch sortingBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(benthosBatchId)); + + for (Batch batch : sortingBatch.getChildBatchs()) { + SortingBatch source = (SortingBatch) batch; + SpeciesBatchFrequency target = new SpeciesBatchFrequency(); + + batchHelper.entityToSpeciesBatchFrequency(source, target); + results.add(target); + } + return Collections.unmodifiableList(results); + } + + @Override + public List<SpeciesBatchFrequency> saveBenthosBatchFrequency(String benthosBatchId, + List<SpeciesBatchFrequency> frequencies) { + Preconditions.checkNotNull(benthosBatchId); + Preconditions.checkNotNull(frequencies); + + // Check that all frequencies have the same length PMFM (before doing any db call) + String pmfmId = null; + for (SpeciesBatchFrequency source : frequencies) { + + if (pmfmId == null) { + pmfmId = source.getLengthStepCaracteristic().getId(); + } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) { + throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic"); + } + } + + getCurrentSession().setFlushMode(FlushMode.COMMIT); + + Integer sortingBatchId = Integer.valueOf(benthosBatchId); + Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(sortingBatchId); + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + + if (catchBatch == null) { + return frequencies; + } + + // Retrieve parent + SortingBatch parentBatch = catchBatchDao.getSortingBatchById(catchBatch, sortingBatchId); + + // Remember child ids, to remove unchanged item (see at bottom in this method) + List<Integer> notUpdatedChildIds = Lists.newArrayList(); + for (Batch batch : parentBatch.getChildBatchs()) { + SortingBatch sortingBatch = (SortingBatch) batch; + notUpdatedChildIds.add(sortingBatch.getId()); + } + + short rankOrder = 0; + List<SortingBatch> batchsToUpdate = Lists.newArrayList(); + for (SpeciesBatchFrequency source : frequencies) { + rankOrder++; + + // Not existing batch + SortingBatch target; + if (source.getId() == null) { + target = SortingBatch.Factory.newInstance(); + + // Fill the sorting batch from the source + batchHelper.speciesBatchFrequencyToEntity(source, target, parentBatch, rankOrder); + + // Create the targeted batch, then update the source id + catchBatchDao.createSortingBatch(target, catchBatch); + source.setId(target.getId()); + } + + // Existing batch + else { + target = catchBatchDao.getSortingBatchById(catchBatch, source.getIdAsInt()); + + // Fill the sorting batch from the source + batchHelper.speciesBatchFrequencyToEntity(source, target, parentBatch, rankOrder); + + // 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) { + catchBatchDao.updateSortingBatch(batchsToUpdate, catchBatch); + } + + if (notUpdatedChildIds.size() > 0) { + for (Integer batchId : notUpdatedChildIds) { + catchBatchDao.removeWithChildren(batchId, catchBatch); + } + } + + getCurrentSession().flush(); + + return Collections.unmodifiableList(frequencies); + } + + + //------------------------------------------------------------------------// + //-- Internal methods --// + //------------------------------------------------------------------------// + + protected void benthosBatchToEntity(SpeciesBatch source, + SortingBatch target, + String parentBatchId, + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) { + batchHelper.speciesBatchToEntity(source, target, parentBatchId, catchBatch, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); + } +} Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceImpl.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Added: svn:eol-style + native Copied: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceService.java (from rev 684, trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java) =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceService.java (rev 0) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceService.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,67 @@ +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 fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException; +import fr.ifremer.tutti.persistence.TuttiPersistenceServiceImplementor; +import fr.ifremer.tutti.persistence.entities.data.CatchBatch; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(readOnly = true) +public interface CatchBatchPersistenceService extends TuttiPersistenceServiceImplementor { + + //------------------------------------------------------------------------// + //-- CatchBatch methods --// + //------------------------------------------------------------------------// + + /** + * Get the catchBatch from the fishing Operation id. + * + * @param fishingOperationId id of the fihsing operation + * @return found catchBatch + * @throws CatchBatchValidationException + */ + CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) throws CatchBatchValidationException; + + /** + * Create the given CatchBatch and return it. + * + * @param bean catchBatch to create + * @return created catchBatch + */ + @Transactional(readOnly = false) + CatchBatch createCatchBatch(CatchBatch bean); + + /** + * Save the given catchBatch and return it. + * + * @param bean batch to save + * @return the saved catchBatch + */ + @Transactional(readOnly = false) + CatchBatch saveCatchBatch(CatchBatch bean); + +} \ No newline at end of file Copied: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java (from rev 684, trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java) =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java (rev 0) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,686 @@ +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 com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +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.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.ReferenceTaxonImpl; +import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus; +import fr.ifremer.tutti.persistence.entities.data.CatchBatch; +import fr.ifremer.tutti.persistence.service.batch.BatchPersistenceHelper; +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.Collection; +import java.util.Map; +import java.util.Set; + +@Service("batchPersistenceService") +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 = "catchBatchDao") + protected CatchBatchExtendDao catchBatchDao; + + @Resource(name = "scientificCruiseCatchBatchValidator") + protected CatchBatchValidator catchBatchValidator; + + @Resource(name = "batchPersistenceHelper") + protected BatchPersistenceHelper batchHelper; + + @Override + public void init() { + super.init(); + catchBatchDao.registerCatchBatchValidator(catchBatchValidator); + } + + @Override + public void close() { + catchBatchDao.unregisterCatchBatchValidator(catchBatchValidator); + super.close(); + } + + //------------------------------------------------------------------------// + //-- CatchBatch methods --// + //------------------------------------------------------------------------// + + @Override + public CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) throws CatchBatchValidationException { + Preconditions.checkNotNull(fishingOperationId); + + Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId)); + Preconditions.checkNotNull(catchBatchId); + + // wenever want to repair anything from Tutti + fr.ifremer.adagio.core.dao.data.batch.CatchBatch source = catchBatchDao.loadFullTree(catchBatchId, true, false); + + CatchBatch result = new CatchBatch(); + result.setId(source.getId()); + result.setCatchTotalWeight(source.getWeight()); + + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch: " + result.getId()); + } + + // Vrac + SortingBatch vracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(), + "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac: " + vracBatch.getId()); + } + result.setCatchTotalSortedCarousselWeight(vracBatch.getWeight()); + result.setCatchTotalSortedTremisWeight(vracBatch.getWeightBeforeSampling()); + { + // Vrac > Species + SortingBatch speciesBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(), + "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); + + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac > Species : " + speciesBatch.getId()); + } + + result.setSpeciesTotalSampleSortedWeight(speciesBatch.getWeight()); + result.setSpeciesTotalSortedWeight(speciesBatch.getWeightBeforeSampling()); + + { + // Vrac > Species > Inert + SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), + "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT); + + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac > Species > Inert: " + inertBatch.getId()); + } + if (inertBatch != null) { + result.setSpeciesTotalInertWeight(inertBatch.getWeight()); + } + + // Vrac > Species > Alive no itemized + SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), + "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac > Species > Alive not itemized: " + livingNotItemizedBatch.getId()); + } + if (livingNotItemizedBatch != null) { + result.setSpeciesTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight()); + } + } + + // Vrac > Benthos + SortingBatch benthosBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(), + "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); + + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac > Benthos: " + benthosBatch.getId()); + } + + result.setBenthosTotalSampleSortedWeight(benthosBatch.getWeight()); + result.setBenthosTotalSortedWeight(benthosBatch.getWeightBeforeSampling()); + + { + // Vrac > Benthos > Inert + SortingBatch inertBatch = catchBatchDao.getSortingBatch(benthosBatch.getChildBatchs(), + "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac > Benthos > Inert: " + inertBatch.getId()); + } + if (inertBatch != null) { + result.setBenthosTotalInertWeight(inertBatch.getWeight()); + } + + // Vrac > Benthos > Alive no itemized + SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(benthosBatch.getChildBatchs(), + "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac > Benthos > Alive not itemized: " + livingNotItemizedBatch.getId()); + } + if (livingNotItemizedBatch != null) { + result.setBenthosTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight()); + } + } + + // TODO : Plancton... + } + + // Hors Vrac + SortingBatch horsVracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(), + "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Hors Vrac: " + horsVracBatch.getId()); + } + if (horsVracBatch != null) { + result.setCatchTotalUnsortedWeight(horsVracBatch.getWeight()); + { + // Hors Vrac > Species + SortingBatch speciesBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(), + "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); + + if (speciesBatch != null) { + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Hors Vrac> Species: " + speciesBatch.getId()); + } + result.setSpeciesTotalUnsortedWeight(speciesBatch.getWeight()); + } + + // Hors Vrac > Benthos + SortingBatch benthosBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(), + "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); + + + if (benthosBatch != null) { + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Hors Vrac> Benthos: " + benthosBatch.getId()); + } + result.setBenthosTotalUnsortedWeight(benthosBatch.getWeight()); + } + + // TODO : Plancton... + } + } + + // Non trié + SortingBatch unsortedBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(), + "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Unsorted: " + unsortedBatch.getId()); + } + if (unsortedBatch != null) { + 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(); + catchBatchToEntity(bean, catchBatch); + catchBatch = catchBatchDao.create(catchBatch); + bean.setId(catchBatch.getId()); + + // Link to fishing operation + getCurrentSession().flush(); + Integer fishingOperationId = bean.getFishingOperation().getIdAsInt(); + 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()); + Preconditions.checkNotNull(bean.getFishingOperation()); + Preconditions.checkNotNull(bean.getFishingOperation().getId()); + + getCurrentSession().enableFetchProfile("batch-with-childs"); + getCurrentSession().setFlushMode(FlushMode.COMMIT); + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(bean.getIdAsInt()); + if (catchBatch == null) { + throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId()); + } + + catchBatchToEntity(bean, catchBatch); + catchBatchDao.update(catchBatch); + getCurrentSession().flush(); + + return bean; + } + + //------------------------------------------------------------------------// + //-- Internal methods --// + //------------------------------------------------------------------------// + + protected void catchBatchToEntity(CatchBatch source, + fr.ifremer.adagio.core.dao.data.batch.CatchBatch target) { + Preconditions.checkNotNull(source.getFishingOperation()); + Preconditions.checkNotNull(source.getFishingOperation().getId()); + + // Retrieve recorder department + Integer recorderDepartmentId = getRecorderDepartmentId(); + + // First initialization (when created) + Integer fishingOperationId = source.getFishingOperation().getIdAsInt(); + 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 + Collection<QuantificationMeasurement> quantificationMeasurements = target.getQuantificationMeasurements(); + Set<QuantificationMeasurement> notChangedQuantificationMeasurements = Sets.newHashSet(); + if (quantificationMeasurements != null) { + notChangedQuantificationMeasurements.addAll(quantificationMeasurements); + } + + // Total Weight + if (source.getCatchTotalWeight() == null) { + // Nothing to do : will be removed later, using notChangedQuantificationMeasurements + } else { + QuantificationMeasurement quantificationMeasurement = catchBatchDao.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 (quantificationMeasurements != null) { + quantificationMeasurements.removeAll(notChangedQuantificationMeasurements); + } +// 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); + + // ----------------------------------------------------------------------------- + // 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()); + batch.setRankOrder((short) 1); + + // Manage childs : + { + if (batch.getChildBatchs() == null) { + batch.setChildBatchs(Lists.<Batch>newArrayList()); + } + + Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE); + + // ----------------------------------------------------------------------------- + // Vrac / Species + // ----------------------------------------------------------------------------- + SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); + + if (speciesBatch == null) { + speciesBatch = SortingBatch.Factory.newInstance(); + batch.getChildBatchs().add(speciesBatch); + } + beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId, + enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES, + source.getSpeciesTotalSampleSortedWeight(), source.getSpeciesTotalSortedWeight()); + speciesBatch.setRankOrder((short) 1); + + { + if (speciesBatch.getChildBatchs() == null) { + speciesBatch.setChildBatchs(Lists.<Batch>newArrayList()); + } + // ----------------------------------------------------------------------------- + // Vrac / Species / Alive not itemized + // ----------------------------------------------------------------------------- + + SortingBatch aliveNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE); + if (aliveNotItemizedBatch == null) { + aliveNotItemizedBatch = SortingBatch.Factory.newInstance(); + speciesBatch.getChildBatchs().add(aliveNotItemizedBatch); + } + beanToEntityReferenceTaxonBatch(target, speciesBatch, aliveNotItemizedBatch, recorderDepartmentId, + enumeration.REFERENCE_TAXON_ID_LIFE, + source.getSpeciesTotalLivingNotItemizedWeight(), null); + aliveNotItemizedBatch.setRankOrder((short) 1); + + // ----------------------------------------------------------------------------- + // 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); + inertBatch.setRankOrder((short) 2); + } + + // ----------------------------------------------------------------------------- + // Vrac > Benthos + // ----------------------------------------------------------------------------- + + SortingBatch benthosBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); + if (benthosBatch == null) { + benthosBatch = SortingBatch.Factory.newInstance(); + batch.getChildBatchs().add(benthosBatch); + } + beanToEntitySortingBatch(target, batch, benthosBatch, recorderDepartmentId, + enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS, + source.getBenthosTotalSampleSortedWeight(), source.getBenthosTotalSortedWeight()); + benthosBatch.setRankOrder((short) 2); + + { + + if (benthosBatch.getChildBatchs() == null) { + benthosBatch.setChildBatchs(Lists.<Batch>newArrayList()); + } + + // ----------------------------------------------------------------------------- + // Vrac / Benthos / Alive not itemized + // ----------------------------------------------------------------------------- + + SortingBatch aliveNotItemizedBatch = catchBatchDao.getSortingBatch(benthosBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE); + if (aliveNotItemizedBatch == null) { + aliveNotItemizedBatch = SortingBatch.Factory.newInstance(); + benthosBatch.getChildBatchs().add(aliveNotItemizedBatch); + } + beanToEntityReferenceTaxonBatch(target, benthosBatch, aliveNotItemizedBatch, recorderDepartmentId, + enumeration.REFERENCE_TAXON_ID_LIFE, + source.getBenthosTotalLivingNotItemizedWeight(), null); + aliveNotItemizedBatch.setRankOrder((short) 1); + + // ----------------------------------------------------------------------------- + // Vrac / Species / Inert (not alive) + // ----------------------------------------------------------------------------- + + SortingBatch inertBatch = catchBatchDao.getSortingBatch(benthosBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT); + if (inertBatch == null) { + inertBatch = SortingBatch.Factory.newInstance(); + benthosBatch.getChildBatchs().add(inertBatch); + } + beanToEntityReferenceTaxonBatch(target, benthosBatch, inertBatch, recorderDepartmentId, + enumeration.REFERENCE_TAXON_ID_INERT, + source.getBenthosTotalInertWeight(), null); + inertBatch.setRankOrder((short) 2); + } + + // TODO plancton, macro déchet... + } + } + + // ----------------------------------------------------------------------------- + // 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); + batch.setRankOrder((short) 2); + + // Manage childs : + { + Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE); + + // ----------------------------------------------------------------------------- + // Hors 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.getSpeciesTotalUnsortedWeight(), null); + speciesBatch.setRankOrder((short) 1); + } + + // ----------------------------------------------------------------------------- + // Hors Vrac > Benthos : + // ----------------------------------------------------------------------------- + { + SortingBatch benthosBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS); + if (benthosBatch == null) { + benthosBatch = SortingBatch.Factory.newInstance(); + batch.getChildBatchs().add(benthosBatch); + } + beanToEntitySortingBatch(target, batch, benthosBatch, recorderDepartmentId, + enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_BENTHOS, + source.getBenthosTotalUnsortedWeight(), null); + benthosBatch.setRankOrder((short) 2); + } + + // TODO : 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); + unsortedBatch.setRankOrder((short) 3); + + } + + protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) { + Map<Integer, SortingBatch> batchByQualitativeValueId = Maps.newHashMap(); + if (parentBatch.getChildBatchs() == null) { + return batchByQualitativeValueId; + } + for (Batch childBatch : parentBatch.getChildBatchs()) { + SortingBatch childSortingBatch = (SortingBatch) childBatch; + SortingMeasurement sm = catchBatchDao.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false); + if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) { + batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), 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) { + + Collection<QuantificationMeasurement> quantificationMeasurements = target.getQuantificationMeasurements(); + Collection<SortingMeasurement> sortingMeasurements = target.getSortingMeasurements(); + + // Create lists to store all updates, then remove not updated items + Set<QuantificationMeasurement> notChangedQuantificationMeasurements = Sets.newHashSet(); + if (quantificationMeasurements != null) { + notChangedQuantificationMeasurements.addAll(quantificationMeasurements); + } + Set<SortingMeasurement> notChangedSortingMeasurements = Sets.newHashSet(); + if (sortingMeasurements != null) { + notChangedSortingMeasurements.addAll(sortingMeasurements); + } + + // 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 (sortingPmfmId == null || sortingQualitativeValueId == null) { + // Nothing to do : will be removed later, using notChangedSortingMeasurements + } else { + SortingMeasurement sm = batchHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId); + notChangedSortingMeasurements.remove(sm); + } + + // Sampling Ratio + if (sampleWeight == null || weight == null) { + target.setSamplingRatio(null); + target.setSamplingRatioText(null); + } else { + String samplingRatioText = weight + "/" + sampleWeight; + samplingRatioText = samplingRatioText.replaceAll(",", "."); + target.setSamplingRatioText(samplingRatioText); + target.setSamplingRatio(weight / sampleWeight); + } + + // Weight + if (sampleWeight == null && weight == null) { + // Nothing to do : will be removed later, using notChangedQuantificationMeasurements + } else { + Float batchReferenceWeight = weight; + if (batchReferenceWeight == null) { + batchReferenceWeight = sampleWeight; + } + QuantificationMeasurement quantificationMeasurement = catchBatchDao.setQuantificationMeasurement(target, + enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true); + notChangedQuantificationMeasurements.remove(quantificationMeasurement); + } + + // Removed not changed measurements (in sorting and quantification measurement lists) + if (quantificationMeasurements != null) { + quantificationMeasurements.removeAll(notChangedQuantificationMeasurements); + } + if (sortingMeasurements != null) { + sortingMeasurements.removeAll(notChangedSortingMeasurements); + } + } + + 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) { + + Collection<QuantificationMeasurement> quantificationMeasurements = target.getQuantificationMeasurements(); + Collection<SortingMeasurement> sortingMeasurements = target.getSortingMeasurements(); + + // Create lists to store all updates, then remove not updated items + Set<QuantificationMeasurement> notChangedQuantificationMeasurements = Sets.newHashSet(); + if (quantificationMeasurements != null) { + notChangedQuantificationMeasurements.addAll(quantificationMeasurements); + } + Set<SortingMeasurement> notChangedSortingMeasurements = Sets.newHashSet(); + if (sortingMeasurements != null) { + notChangedSortingMeasurements.addAll(sortingMeasurements); + } + + // 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 ((sampleWeight == null || weight == null)) { + target.setSamplingRatio(null); + target.setSamplingRatioText(null); + } else { + String samplingRatioText = weight + "/" + sampleWeight; + samplingRatioText = samplingRatioText.replaceAll(",", "."); + target.setSamplingRatioText(samplingRatioText); + target.setSamplingRatio(weight / sampleWeight); + } + + // Weight + if ((sampleWeight == null && weight == null)) { + // Nothing to do : will be removed later, using notChangedQuantificationMeasurements + } else { + Float batchReferenceWeight = weight; + if (batchReferenceWeight == null) { + batchReferenceWeight = sampleWeight; + } + QuantificationMeasurement quantificationMeasurement = catchBatchDao.setQuantificationMeasurement(target, + enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true); + notChangedQuantificationMeasurements.remove(quantificationMeasurement); + } + + // Removed not changed measurements (in sorting and quantification measurement lists) + if (quantificationMeasurements != null) { + quantificationMeasurements.removeAll(notChangedQuantificationMeasurements); + } + if (sortingMeasurements != null) { + sortingMeasurements.removeAll(notChangedSortingMeasurements); + } + } + + protected Integer getRecorderDepartmentId() { + // TODO BL : voir si on peut récupérer le departement (du 1er saisisseur ?) + return enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT; + } +} Added: 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 (rev 0) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceService.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,111 @@ +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 fr.ifremer.tutti.persistence.TuttiPersistenceServiceImplementor; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * Service to persist *species* {@link SpeciesBatch}. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.2 + */ +@Transactional(readOnly = true) +public interface SpeciesBatchPersistenceService extends TuttiPersistenceServiceImplementor { + + //------------------------------------------------------------------------// + //-- SpeciesBatch methods --// + //------------------------------------------------------------------------// + + /** + * Get the batch parent of 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.2 + */ + BatchContainer<SpeciesBatch> getRootSpeciesBatch(String fishingOperationId); + + @Transactional(readOnly = false) + SpeciesBatch createSpeciesBatch(SpeciesBatch bean, String parentBatchId); + + @Transactional(readOnly = false) + SpeciesBatch saveSpeciesBatch(SpeciesBatch bean); + + @Transactional(readOnly = false) + void deleteSpeciesBatch(String id); + + @Transactional(readOnly = false) + void deleteSpeciesSubBatch(String id); + + /** + * Change the species in the given {@code batchId} and in all his + * sub batches. + * + * @param batchId id of the root species batch to treat + * @param species species to affect to all batches + */ + @Transactional(readOnly = false) + void changeSpeciesBatchSpecies(String batchId, Species species); + + //------------------------------------------------------------------------// + //-- SpeciesBatchFrequency methods (for species) --// + //------------------------------------------------------------------------// + + /** + * 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); + +} Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceService.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Added: svn:eol-style + native Added: 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 (rev 0) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,369 @@ +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 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.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import fr.ifremer.tutti.persistence.service.batch.BatchPersistenceHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.FlushMode; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * Default implementation of {@link SpeciesBatchPersistenceService}. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.2 + */ +@Service("speciesBatchPersistenceService") +public class SpeciesBatchPersistenceServiceImpl extends AbstractPersistenceService + implements SpeciesBatchPersistenceService { + + /** Logger. */ + private static final Log log = + LogFactory.getLog(SpeciesBatchPersistenceServiceImpl.class); + + @Resource(name = "catchBatchDao") + protected CatchBatchExtendDao catchBatchDao; + + @Resource(name = "batchPersistenceHelper") + protected BatchPersistenceHelper batchHelper; + + //------------------------------------------------------------------------// + //-- SpeciesBatch methods --// + //------------------------------------------------------------------------// + + @Override + public BatchContainer<SpeciesBatch> getRootSpeciesBatch(String fishingOperationId) { + Preconditions.checkNotNull(fishingOperationId); + + // Load batch tree + Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId)); + Preconditions.checkNotNull(catchBatchId); + + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + Preconditions.checkNotNull(catchBatch); + + Collection<Batch> catchBatchChilds = catchBatch.getChildBatchs(); + // Vrac / Species + SortingBatch vracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatchChilds, + "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID, + "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); + + // container of speciesBatch is arbitraty put on vrac type (there is + // no common ancestor for all species batch). + BatchContainer<SpeciesBatch> result = new BatchContainer<SpeciesBatch>(); + result.setId(vracSpeciesBatch.getId()); + + for (Batch batch1 : vracSpeciesBatch.getChildBatchs()) { + SortingBatch source = (SortingBatch) batch1; + + // evict some special batches : Life (or Biota) and Inert + if (source.getReferenceTaxon() != null + && !enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) + && !enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId())) { + + SpeciesBatch target = new SpeciesBatch(); + batchHelper.entityToSpeciesBatch(source, target); + result.addChildren(target); + + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Vrac > Species > " + target.getSpecies().getReferenceTaxonId() + " : " + target.getId()); + } + } + } + + // Hors-Vrac / Species + SortingBatch horsVracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatchChilds, + "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID, + "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); + if (horsVracSpeciesBatch != null) { + for (Batch batch : horsVracSpeciesBatch.getChildBatchs()) { + + SpeciesBatch target = new SpeciesBatch(); + batchHelper.entityToSpeciesBatch((SortingBatch) batch, target); + result.addChildren(target); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Hors Vrac > Species > " + target.getSpecies().getReferenceTaxonId() + " : " + target.getId()); + } + } + } + + 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()); + + getCurrentSession().setFlushMode(FlushMode.COMMIT); + + // Load full batch tree + Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(bean.getFishingOperation().getIdAsInt()); + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + + SortingBatch batch = SortingBatch.Factory.newInstance(); + speciesBatchToEntity(bean, batch, parentBatchId, catchBatch); + batch = catchBatchDao.createSortingBatch(batch, catchBatch); + + bean.setId(batch.getId()); + + getCurrentSession().flush(); + + return bean; + } + + @Override + public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) { + Preconditions.checkNotNull(bean); + Preconditions.checkNotNull(bean.getId()); + + // Load batch tree + Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(bean.getIdAsInt()); + Preconditions.checkNotNull(catchBatchId); + + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + Preconditions.checkNotNull(catchBatch); + + getCurrentSession().setFlushMode(FlushMode.COMMIT); + + SortingBatch batch = catchBatchDao.getSortingBatchById(catchBatch, bean.getIdAsInt()); + String parentBatchId = null; + if (bean.getParentBatch() != null) { + parentBatchId = bean.getParentBatch().getId(); + } + speciesBatchToEntity(bean, batch, parentBatchId, catchBatch); + catchBatchDao.updateSortingBatch(batch, catchBatch); + getCurrentSession().flush(); + + return bean; + } + + @Override + public void deleteSpeciesBatch(String id) { + Preconditions.checkNotNull(id); + + getCurrentSession().setFlushMode(FlushMode.COMMIT); + + catchBatchDao.removeWithChildren(Integer.valueOf(id)); + + getCurrentSession().flush(); + } + + @Override + public void deleteSpeciesSubBatch(String id) { + Preconditions.checkNotNull(id); + deleteSpeciesBatch(id); + } + + @Override + public void changeSpeciesBatchSpecies(String batchId, Species species) { + + Preconditions.checkNotNull(batchId); + Preconditions.checkNotNull(species); + Preconditions.checkNotNull(species.getReferenceTaxonId()); + + catchBatchDao.setSortingBatchReferenceTaxon(batchId, species.getReferenceTaxonId()); + } + + //------------------------------------------------------------------------// + //-- SpeciesBatchFrequency methods --// + //------------------------------------------------------------------------// + + @Override + public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency( + String speciesBatchId) { + Preconditions.checkNotNull(speciesBatchId); + + List<SpeciesBatchFrequency> results = Lists.newArrayList(); + + Integer sortingBatchId = Integer.valueOf(speciesBatchId); + Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(sortingBatchId); + Preconditions.checkNotNull( + catchBatchId, + "Could not find catchBatch for speciesBatch: " + speciesBatchId); + + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = + catchBatchDao.loadFullTree(catchBatchId); + + SortingBatch sortingBatch = catchBatchDao.getSortingBatchById( + catchBatch, sortingBatchId); + + List<SortingBatch> frequencyChilds = batchHelper.getFrequencyChilds(sortingBatch); + for (SortingBatch child : frequencyChilds) { + SpeciesBatchFrequency target = new SpeciesBatchFrequency(); + + batchHelper.entityToSpeciesBatchFrequency(child, target); + results.add(target); + } + return Collections.unmodifiableList(results); + } + + @Override + public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency( + String speciesBatchId, + List<SpeciesBatchFrequency> frequencies) { + Preconditions.checkNotNull(speciesBatchId); + Preconditions.checkNotNull(frequencies); + + List<SpeciesBatchFrequency> notNullFrequencies = Lists.newArrayList(); + + // Check that all frequencies have the same length PMFM (before doing any db call) + // and remove null frequencies + String pmfmId = null; + for (SpeciesBatchFrequency source : frequencies) { + + if (source.getLengthStepCaracteristic() != null) { + if (pmfmId == null) { + pmfmId = source.getLengthStepCaracteristic().getId(); + } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) { + throw new DataIntegrityViolationException("Batch frequencies under one SpeciesBatch must have all the same lengthStepCaracteristic"); + } + notNullFrequencies.add(source); + } + } + + getCurrentSession().setFlushMode(FlushMode.COMMIT); + + Integer sortingBatchId = Integer.valueOf(speciesBatchId); + Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(sortingBatchId); + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId); + + if (catchBatch == null) { + return notNullFrequencies; + } + + // Retrieve parent + SortingBatch parentBatch = catchBatchDao.getSortingBatchById(catchBatch, sortingBatchId); + + // Remember child ids, to remove unchanged item (see at bottom in this method) + List<Integer> notUpdatedChildIds = Lists.newArrayList(); + List<SortingBatch> frequencyChilds = batchHelper.getFrequencyChilds(parentBatch); + for (SortingBatch child : frequencyChilds) { + notUpdatedChildIds.add(child.getId()); + } +// for (Batch batch : parentBatch.getChildBatchs()) { +// SortingBatch sortingBatch = (SortingBatch) batch; +// notUpdatedChildIds.add(sortingBatch.getId()); +// } + + short rankOrder = 0; + List<SortingBatch> batchsToUpdate = Lists.newArrayList(); + for (SpeciesBatchFrequency source : notNullFrequencies) { + rankOrder++; + + SortingBatch target; + if (source.getId() == null) { + + // Not existing batch + target = SortingBatch.Factory.newInstance(); + + // Fill the sorting batch from the source + batchHelper.speciesBatchFrequencyToEntity(source, target, parentBatch, rankOrder); + + // Create the targeted batch, then update the source id + catchBatchDao.createSortingBatch(target, catchBatch); + + // push back id of created sortingBatch + source.setId(target.getId()); + + if (log.isInfoEnabled()) { + log.info("Create frequency sortingBatch(" + rankOrder + "): " + target.getId()); + } + } else { + + // Existing batch + target = catchBatchDao.loadSortingBatch(source.getIdAsInt(), catchBatch); + + // Fill the sorting batch from the source + batchHelper.speciesBatchFrequencyToEntity(source, target, parentBatch, rankOrder); + + // Add the batch into a list (will be update later, using this list) + batchsToUpdate.add(target); + + // Remove id from id to remove + notUpdatedChildIds.remove(target.getId()); + + if (log.isInfoEnabled()) { + log.info("Update frequency sortingBatch(" + rankOrder + "): " + target.getId()); + } + } + } + + if (batchsToUpdate.size() > 0) { + + // update some batchs + catchBatchDao.updateSortingBatch(batchsToUpdate, catchBatch); + } + + if (notUpdatedChildIds.size() > 0) { + + // Remove obsolete frequencies + for (Integer batchId : notUpdatedChildIds) { + + if (log.isInfoEnabled()) { + log.info("Remove obsolete frequency sortingBatch: " + batchId); + } + catchBatchDao.removeWithChildren(batchId, catchBatch); + } + } + + getCurrentSession().flush(); + + return Collections.unmodifiableList(notNullFrequencies); + } + + //------------------------------------------------------------------------// + //-- Internal methods --// + //------------------------------------------------------------------------// + + protected void speciesBatchToEntity(SpeciesBatch source, + SortingBatch target, + String parentBatchId, + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) { + batchHelper.speciesBatchToEntity(source, target, parentBatchId, catchBatch, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES); + } + +} Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.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/TuttiPersistenceServiceLocator.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java 2013-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java 2013-03-27 21:49:05 UTC (rev 693) @@ -80,11 +80,21 @@ FishingOperationPersistenceService.class); } - public static BatchPersistenceService getBatchPersistenceService() { + public static CatchBatchPersistenceService getCatchBatchPersistenceService() { return getPersistenceService("batchPersistenceService", - BatchPersistenceService.class); + CatchBatchPersistenceService.class); } + public static SpeciesBatchPersistenceService getSpeciesBatchPersistenceService() { + return getPersistenceService("speciesBatchPersistenceService", + SpeciesBatchPersistenceService.class); + } + + public static BenthosBatchPersistenceService getBenthosBatchPersistenceService() { + return getPersistenceService("benthosBatchPersistenceService", + BenthosBatchPersistenceService.class); + } + public static PlanktonBatchPersistenceService getPlanktonBatchPersistenceService() { return getPersistenceService("planktonBatchPersistenceService", PlanktonBatchPersistenceService.class); Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/batch/BatchPersistenceHelper.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/batch/BatchPersistenceHelper.java (rev 0) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/batch/BatchPersistenceHelper.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,603 @@ +package fr.ifremer.tutti.persistence.service.batch; + +/* + * #%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 com.google.common.collect.Lists; +import com.google.common.collect.Sets; +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.measure.Measurement; +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.pmfm.Pmfm; +import fr.ifremer.adagio.core.dao.referential.pmfm.QualitativeValue; +import fr.ifremer.adagio.core.dao.referential.pmfm.QualitativeValueImpl; +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.AbstractPersistenceService; +import fr.ifremer.tutti.persistence.service.ReferentialPersistenceService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.io.Serializable; +import java.text.MessageFormat; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +/** + * Helper around batches. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.2 + */ +@Component("batchPersistenceHelper") +public class BatchPersistenceHelper extends AbstractPersistenceService { + + /** Logger. */ + private static final Log log = + LogFactory.getLog(BatchPersistenceHelper.class); + + @Resource(name = "referentialPersistenceService") + protected ReferentialPersistenceService referentialService; + + @Resource(name = "catchBatchDao") + protected CatchBatchExtendDao catchBatchDao; + + public List<SortingBatch> getFrequencyChilds(SortingBatch sortingBatch) { + List<SortingBatch> result = Lists.newArrayList(); + + for (Batch batch : sortingBatch.getChildBatchs()) { + SortingBatch child = (SortingBatch) batch; + if (isFrequencyBatch(child)) { + result.add(child); + } + } + return result; + } + + public List<SortingBatch> getNotFrequencyChilds(SortingBatch sortingBatch) { + List<SortingBatch> result = Lists.newArrayList(); + + for (Batch batch : sortingBatch.getChildBatchs()) { + SortingBatch child = (SortingBatch) batch; + if (isFrequencyBatch(child)) { + result.add(child); + } + } + return result; + } + + /** + * Check if the given {@code sortingBatch} is a frequency one. + * <p/> + * We test that: + * <ul> + * <li>batch has exactly one measurement</li> + * <li>the measurement pmfm is not a sample category</li> + * </ul> + * + * @param sortingBatch batch to check + * @return {@code true} if given batch is a frequency batch, + * {@code false} otherwise. + */ + protected boolean isFrequencyBatch(SortingBatch sortingBatch) { + boolean result = false; + if (sortingBatch.getSortingMeasurements().size() == 1) { + SortingMeasurement sm + = sortingBatch.getSortingMeasurements().iterator().next(); + Pmfm pmfm = sm.getPmfm(); + SampleCategoryEnum sampleCategoryByPmfmId = + enumeration.getSampleCategoryByPmfmId(pmfm.getId()); + result = sampleCategoryByPmfmId == null; + + } + return result; + } + + public SpeciesBatch entityToSpeciesBatch(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 = catchBatchDao.getInheritedSortingMeasurement(source, enumeration.PMFM_ID_SORTED_UNSORTED); + } + if (sm != null) { + SampleCategoryEnum sampleCategory = enumeration.getSampleCategoryByPmfmId(sm.getPmfm().getId()); + if (sampleCategory != null) { + Integer qualitativeId = null; + if (sm.getQualitativeValue() != null) { + qualitativeId = sm.getQualitativeValue().getId(); + } + setSampleCategoryQualitative(target, sm.getPmfm().getId(), sm.getNumericalValue(), sm.getAlphanumericalValue(), qualitativeId); + } + } + + // 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); + } + //FIXME-TC Check the test is still ok? + //FIXME-TC We should a stronger test +// if (target.getSampleCategoryType() != null && source.getChildBatchs().size() > 0) { + if (target.getSampleCategoryType() != null) { + List<SpeciesBatch> targetChilds = Lists.newArrayList(); + for (Batch batch : source.getChildBatchs()) { + SortingBatch sourceChild = (SortingBatch) batch; + SpeciesBatch targetChild = new SpeciesBatch(); + entityToSpeciesBatch(sourceChild, targetChild); + if (log.isInfoEnabled()) { + log.info("Loaded CatchBatch Hors Vrac > Benthos > " + target.getSpecies().getReferenceTaxonId() + " : " + target.getId()); + } + if (targetChild.getSampleCategoryValue() != null) { + targetChilds.add(targetChild); + targetChild.setParentBatch(target); + } + } + target.setChildBatchs(targetChilds); + } + + return target; + } + + public void entityToSpeciesBatchFrequency(SortingBatch source, + SpeciesBatchFrequency target) { + + target.setId(source.getId()); + + target.setNumber(source.getIndividualCount()); + target.setWeight(source.getWeight()); + target.setComment(source.getComments()); + + Preconditions.checkState(source.getSortingMeasurements().size() == 1, "SortingBatch [" + source.getId() + "] need exactly one sortingMeasurement (to store the length step category), but had " + source.getSortingMeasurements().size()); + SortingMeasurement sm = source.getSortingMeasurements().iterator().next(); + Preconditions.checkNotNull(sm.getPmfm(), "SortingMeasurement [" + sm.getId() + "] can not have a null pmfm"); + Preconditions.checkNotNull(sm.getPmfm().getId(), "SortingMeasurement [" + sm.getId() + "] can not have a pmfm with null id"); + + // Length step category + Caracteristic lengthStepCaracteristic = + referentialService.getCaracteristic(sm.getPmfm().getId()); + target.setLengthStepCaracteristic(lengthStepCaracteristic); + + // Length + target.setLengthStep(sm.getNumericalValue()); + } + + public void speciesBatchToEntity(SpeciesBatch source, + SortingBatch target, + String parentBatchId, + fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch, + Integer batchPmfm) { + + Preconditions.checkNotNull(source.getFishingOperation()); + Preconditions.checkNotNull(source.getFishingOperation().getId()); + + // Retrieve recorder department + Integer recorderDepartmentId = getRecorderDepartmentId(); + + Collection<QuantificationMeasurement> quantificationMeasurements = target.getQuantificationMeasurements(); + Collection<SortingMeasurement> sortingMeasurements = target.getSortingMeasurements(); + + // Create lists to store all updates, then remove not updated items + + Set<QuantificationMeasurement> notChangedQuantificationMeasurements = Sets.newHashSet(); + if (quantificationMeasurements != null) { + notChangedQuantificationMeasurements.addAll(quantificationMeasurements); + } + Set<SortingMeasurement> notChangedSortingMeasurements = Sets.newHashSet(); + if (sortingMeasurements != null) { + notChangedSortingMeasurements.addAll(sortingMeasurements); + } + + // 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, batchPmfm); + } + + // 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) { + rankOrder += (short) source.getParentBatch().getChildBatchs().size(); + } else if (target.getParentBatch() != null && target.getParentBatch().getChildBatchs() != null) { + rankOrder += (short) target.getParentBatch().getChildBatchs().size(); + } + target.setRankOrder(rankOrder); + } + + // Force subgroup count to '1', as Allegro + target.setSubgroupCount(1f); + + // Weight or SampleCategoryWeight + if (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 = catchBatchDao.setQuantificationMeasurement(target, + enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true); + notChangedQuantificationMeasurements.remove(quantificationMeasurement); + } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) { + QuantificationMeasurement quantificationMeasurement = catchBatchDao.setQuantificationMeasurement(target, + enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true); + notChangedQuantificationMeasurements.remove(quantificationMeasurement); + } + + // Sampling Ratio + if (source.getSampleCategoryWeight() == null || source.getWeight() == null) { + target.setSamplingRatio(null); + target.setSamplingRatioText(null); + } else { + String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight(); + samplingRatioText = samplingRatioText.replaceAll(",", "."); + target.setSamplingRatioText(samplingRatioText); + target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight()); + QuantificationMeasurement quantificationMeasurement = catchBatchDao.setQuantificationMeasurement(target, + enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true); + notChangedQuantificationMeasurements.remove(quantificationMeasurement); + } + + // Sorting measurement + if ((source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) { + // Nothing to do : will be removed later, using notChangedSortingMeasurements + } else { + Integer pmfmId = source.getSampleCategoryType().getFieldValue(); + // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch) + if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) { + SortingMeasurement sortingMeasurement = setSortingMeasurement(target, recorderDepartmentId, + source.getSampleCategoryType(), source.getSampleCategoryValue()); + notChangedSortingMeasurements.remove(sortingMeasurement); + } + } + + // Individual count + target.setIndividualCount(source.getNumber()); + + // Species + ReferenceTaxon referenceTaxon; + if (source.getSpecies() == null || parentBatchId != null) { + referenceTaxon = null; + } else { + referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId()); + } + target.setReferenceTaxon(referenceTaxon); + + // QualityFlag + String qualityFlag; + if (source.isSpeciesToConfirm()) { + qualityFlag = enumeration.QUALITY_FLAG_CODE_DOUBTFUL; + } else { + qualityFlag = enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED; + } + target.setQualityFlag(load(QualityFlagImpl.class, qualityFlag)); + + // Comments + 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 (quantificationMeasurements != null) { + quantificationMeasurements.removeAll(notChangedQuantificationMeasurements); + } + if (sortingMeasurements != null) { + sortingMeasurements.removeAll(notChangedSortingMeasurements); + } +// 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, + Integer batchPmfmId) { + + Preconditions.checkNotNull(target); + Preconditions.checkNotNull(source.getFishingOperation()); + Preconditions.checkNotNull(source.getFishingOperation().getId()); + + // Load existing parent and root + SortingBatch parentBatch; + if (parentBatchIdStr != null) { + parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(parentBatchIdStr)); + } + + // Or retrieve parent batch, from pmfm id + else { + // Retrieve category type + Integer pmfmId = source.getSampleCategoryType().getFieldValue(); + 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, batchPmfmId); + + // 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); + } + + public Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) { + if (value == null) + return null; + Integer qualitativeValueId = null; + if (value instanceof CaracteristicQualitativeValue) { + CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value; + qualitativeValueId = cqValue.getIdAsInt(); + } else if (value instanceof String) { + qualitativeValueId = Integer.valueOf((String) value); + } + return qualitativeValueId; + } + + public 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 = enumeration.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.equals(qv.getIdAsInt())) { + value = qv; + break; + } + } + target.setSampleCategoryValue(value); + } + + public void speciesBatchFrequencyToEntity(SpeciesBatchFrequency source, + SortingBatch target, + SortingBatch parentBatch, + short rankOrder) { + Preconditions.checkNotNull(source.getBatch()); + Preconditions.checkNotNull(source.getBatch().getId()); + + // Retrieve recorder department + Integer recorderDepartmentId = getRecorderDepartmentId(); + + Collection<QuantificationMeasurement> quantificationMeasurements = target.getQuantificationMeasurements(); + Collection<SortingMeasurement> sortingMeasurements = target.getSortingMeasurements(); + + // Create lists to store all updates, then remove not updated items + Set<QuantificationMeasurement> notChangedQuantificationMeasurements = Sets.newHashSet(); + if (quantificationMeasurements != null) { + notChangedQuantificationMeasurements.addAll(quantificationMeasurements); + } + Set<SortingMeasurement> notChangedSortingMeasurements = Sets.newHashSet(); + if (sortingMeasurements != null) { + notChangedSortingMeasurements.addAll(sortingMeasurements); + } + + // 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 (source.getWeight() == null) { + // Nothing to do : will be removed later, using notChangedSortingMeasurements + } else { + QuantificationMeasurement quantificationMeasurement = catchBatchDao.setQuantificationMeasurement( + target, + enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true); + notChangedQuantificationMeasurements.remove(quantificationMeasurement); + } + + // Sorting measurement + if ((source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) { + // Nothing to do : will be removed later, using notChangedSortingMeasurements + } else { + Integer pmfmId = source.getLengthStepCaracteristic().getIdAsInt(); + SortingMeasurement sortingMeasurement = setSortingMeasurement(target, recorderDepartmentId, pmfmId, + source.getLengthStep()); + notChangedSortingMeasurements.remove(sortingMeasurement); + } + + // Individual count + target.setIndividualCount(source.getNumber()); + + // Species + target.setReferenceTaxon(null); + + // QualityFlag + target.setQualityFlag(parentBatch.getQualityFlag()); + + // Comments + 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 (quantificationMeasurements != null) { + quantificationMeasurements.removeAll(notChangedQuantificationMeasurements); + } + if (sortingMeasurements != null) { + sortingMeasurements.removeAll(notChangedSortingMeasurements); + } + +// 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 Integer getRecorderDepartmentId() { + // TODO BL : voir si on peut récupérer le departement (du 1er saisisseur ?) + return enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT; + } + + public void setMeasurement(Measurement measurement, + Caracteristic caracteristic, + Serializable value) { + if (caracteristic.getCaracteristicType() == CaracteristicType.TEXT) { + measurement.setAlphanumericalValue((String) value); + } else if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER) { + measurement.setNumericalValue((Float) value); + } else if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { + Integer qvId; + if (value instanceof CaracteristicQualitativeValue) { + qvId = ((CaracteristicQualitativeValue) value).getIdAsInt(); + } else if (value instanceof Integer) { + qvId = (Integer) value; + } + // TODO BL : not used ? => to remove + else { + qvId = Integer.valueOf(value.toString()); + } + QualitativeValue qv = load(QualitativeValueImpl.class, qvId); + measurement.setQualitativeValue(qv); + } + } + + public SortingMeasurement setSortingMeasurement( + SortingBatch sortingBatch, Integer recorderDepartmentId, + SampleCategoryEnum sampleCategory, Serializable value) { + Preconditions.checkNotNull(sampleCategory); + Preconditions.checkNotNull(value); + + Integer pmfmId = sampleCategory.getFieldValue(); + + Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId); + SortingMeasurement sortingMeasurement = catchBatchDao.getSortingMeasurement( + sortingBatch, pmfmId, recorderDepartmentId, true); + setMeasurement(sortingMeasurement, caracteristic, value); + return sortingMeasurement; + } + + public SortingMeasurement setSortingMeasurement( + SortingBatch sortingBatch, Integer recorderDepartmentId, + Integer pmfmId, Serializable value) { + Preconditions.checkNotNull(pmfmId); + Preconditions.checkNotNull(value); + + Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId); + SortingMeasurement sortingMeasurement = catchBatchDao.getSortingMeasurement( + sortingBatch, pmfmId, recorderDepartmentId, true); + setMeasurement(sortingMeasurement, caracteristic, value); + return sortingMeasurement; + } +} Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/batch/BatchPersistenceHelper.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/batch/ScientificCruiseCatchBatchValidator.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/batch/ScientificCruiseCatchBatchValidator.java 2013-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/batch/ScientificCruiseCatchBatchValidator.java 2013-03-27 21:49:05 UTC (rev 693) @@ -33,7 +33,7 @@ import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationError; import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidator; import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement; -import fr.ifremer.tutti.persistence.service.BatchPersistenceService; +import fr.ifremer.tutti.persistence.service.CatchBatchPersistenceService; import fr.ifremer.tutti.persistence.service.TuttiEnumerationFile; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -54,7 +54,7 @@ LogFactory.getLog(ScientificCruiseCatchBatchValidator.class); @Autowired - protected BatchPersistenceService batchService; + protected CatchBatchPersistenceService batchService; @Autowired protected CatchBatchExtendDao catchBatchDao; Deleted: 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-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -1,201 +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.collect.Maps; -import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException; -import fr.ifremer.tutti.persistence.DatabaseResource; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -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 java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * To test {@link BatchPersistenceService} for read operation. - * - * @author tchemit <chemit@codelutin.com> - * @since 1.0 - */ -public class BatchPersistenceServiceReadTest { - - @ClassRule - public static final DatabaseResource dbResource = DatabaseResource.writeDb(); - - 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(expected = CatchBatchValidationException.class) - public void getCatchBatchFromFishingOperation() throws Exception { - - //TODO-TC Change test when data will be Tutti-aware - // old CGFS tree structure is still not valid - service.getCatchBatchFromFishingOperation(fishingOperation.getId()); - } - - @Ignore - @Test - public void getRootSpeciesBatch(/*String fishingOperationId*/) { - //TODO Do me! - service.getRootSpeciesBatch(fishingOperation.getId()); - } - - @Ignore - @Test - public void getAllSpeciesBatchFrequency(/*String speciesBatchId*/) { - //TODO Do me! - } - - @Ignore - @Test - public void getRootBenthosBatch(/*String fishingOperationId*/) { - //TODO Do me! - } - - - 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) { - BatchContainer<SpeciesBatch> rootSpeciesBatch = TuttiPersistenceServiceLocator.getBatchPersistenceService().getRootSpeciesBatch(fishingOperationId); - return getSpeciesBatch(speciesBatchId, rootSpeciesBatch.getChildren()); - } - - 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; - } - -} Deleted: 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-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -1,884 +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.collect.Lists; -import com.google.common.collect.Maps; -import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException; -import fr.ifremer.tutti.persistence.DatabaseResource; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -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 fr.ifremer.tutti.persistence.entities.referential.TuttiLocation; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.dao.DataRetrievalFailureException; - -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.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * To test {@link BatchPersistenceService} for write operation. - * - * @author tchemit <chemit@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 ReferentialPersistenceService referentialService; - - /* - * Entities prepared in setUp() : - * */ - 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(); - 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()); - calendar.add(Calendar.MONTH, 1); // add one month - cruise.setEndDate(calendar.getTime()); - List<TuttiLocation> allHarbour = referentialService.getAllHarbour(); - Assert.assertNotNull(allHarbour); - Assert.assertTrue(allHarbour.size() > 1); - cruise.setDepartureLocation(allHarbour.get(0)); - cruise.setReturnLocation(allHarbour.get(1)); - - 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 = service.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; - SpeciesBatch esp2Batch; - SpeciesBatch frequenciesParentBatch; - SpeciesBatch batch; - 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 - // ----------------------------------------------------------------------------- - BatchContainer<SpeciesBatch> rootSpeciesBatc = service.getRootSpeciesBatch(fishingOperationWithEmptyBatch.getId()); - List<SpeciesBatch> rootSpeciesBatch = rootSpeciesBatc.getChildren(); - 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) - // Note: use a new list (everything list coming from service are not modifiable) - createdFrequencies = Lists.newArrayList(createdFrequencies); - createdFrequencies.remove(createdFrequencies.size() - 1); - - List<SpeciesBatchFrequency> savedFrequencies = service.saveSpeciesBatchFrequency(frequenciesParentBatch.getId(), createdFrequencies); - 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); - } - } - - - @Ignore - @Test - public void createAndSaveBenthosBatchAndFrequencies() { - SpeciesBatch esp1Batch; - SpeciesBatch esp2Batch; - SpeciesBatch frequenciesParentBatch; - SpeciesBatch batch; - 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); - - assertCreateAndReloadBenthosBatch(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); - - assertCreateAndReloadBenthosBatch(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); - - assertCreateAndReloadBenthosBatch(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); - - assertCreateAndReloadBenthosBatch(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); - - assertCreateAndReloadBenthosBatch(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.saveBenthosBatch(batch); - assertSpeciesBatch(savedBatch, batch, false); - SpeciesBatch reloadedBatch = getBenthosBatch(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.getRootSpeciesBatch(fishingOperationWithEmptyBatch.getId()).getChildren(); - 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); - } - - @Ignore - @Test - public void deleteBenthosBatch(/* 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); - assertCreateAndReloadBenthosBatch(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); - assertCreateAndReloadBenthosBatch(batch, esp1Batch.getId()); - - // Try to remove - service.deleteBenthosBatch(esp1Batch.getId()); - - // Check if remove - try { - batch = getBenthosBatch(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 assertCreateAndReloadBenthosBatch(SpeciesBatch batch, String parentBatchId) { - batch.setFishingOperation(fishingOperationWithEmptyBatch); - - // Create batch - SpeciesBatch createdBatch = service.createBenthosBatch(batch, parentBatchId); - assertSpeciesBatch(batch, createdBatch, false); - - // then reload (for round trip check) - SpeciesBatch reloadedBatch = getBenthosBatch(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 = null; - try { - reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId); - } catch (CatchBatchValidationException e) { - Assert.fail(e.getMessage()); - } - 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 = null; - try { - reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId); - } catch (CatchBatchValidationException e) { - Assert.fail(e.getMessage()); - } - 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.getRootSpeciesBatch(fishingOperationId).getChildren()); - } - - protected SpeciesBatch getBenthosBatch(String fishingOperationId, String speciesBatchId) { - return getSpeciesBatch(speciesBatchId, service.getRootBenthosBatch(fishingOperationId).getChildren()); - } - - 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; - } -} Added: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceReadTest.java =================================================================== --- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceReadTest.java (rev 0) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceReadTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,188 @@ +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.collect.Maps; +import fr.ifremer.tutti.persistence.DatabaseResource; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +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 java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * To test {@link BenthosBatchPersistenceService} for read operation. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +@Ignore +public class BenthosBatchPersistenceServiceReadTest { + + @ClassRule + public static final DatabaseResource dbResource = DatabaseResource.writeDb(); + + protected BenthosBatchPersistenceService service; + + protected FishingOperationPersistenceService fishingOperationService; + + protected FishingOperation fishingOperation; + + @Before + public void setUp() throws Exception { + service = TuttiPersistenceServiceLocator.getBenthosBatchPersistenceService(); + 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()); + } + + @Ignore + @Test + public void getRootBenthosBatch(/*String fishingOperationId*/) { + //TODO Do me! + service.getRootBenthosBatch(fishingOperation.getId()); + } + + @Ignore + @Test + public void getAllBenthosBatchFrequency(/*String speciesBatchId*/) { + //TODO Do me! + service.getAllBenthosBatchFrequency(fishingOperation.getId()); + } + + + 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 SpeciesBatch getSpeciesBatch(String fishingOperationId, + String speciesBatchId) { + BatchContainer<SpeciesBatch> rootSpeciesBatch = service.getRootBenthosBatch(fishingOperationId); + return getSpeciesBatch(speciesBatchId, rootSpeciesBatch.getChildren()); + } + + 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/BenthosBatchPersistenceServiceReadTest.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Added: svn:eol-style + native Added: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceWriteTest.java =================================================================== --- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceWriteTest.java (rev 0) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BenthosBatchPersistenceServiceWriteTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,533 @@ +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.collect.Lists; +import com.google.common.collect.Maps; +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 fr.ifremer.tutti.persistence.entities.referential.TuttiLocation; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.springframework.dao.DataRetrievalFailureException; + +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.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * To test {@link BenthosBatchPersistenceService} for write operation. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +public class BenthosBatchPersistenceServiceWriteTest { + + @ClassRule + public static final DatabaseResource dbResource = DatabaseResource.writeDb(); + + protected BenthosBatchPersistenceService service; + + protected CatchBatchPersistenceService catchBatchService; + + protected CruisePersistenceService cruiseService; + + protected FishingOperationPersistenceService fishingOperationService; + + protected ReferentialPersistenceService referentialService; + + /* + * Entities prepared in setUp() : + * */ + 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.getBenthosBatchPersistenceService(); + cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService(); + catchBatchService = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService(); + fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService(); + referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService(); + + species = referentialService.getAllSpecies(); + assertNotNull(species); + assertTrue(species.size() > 2); + + cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId()); + cruise.setId((String) null); + Calendar calendar = new GregorianCalendar(); + cruise.setBeginDate(calendar.getTime()); + calendar.add(Calendar.MONTH, 1); // add one month + cruise.setEndDate(calendar.getTime()); + List<TuttiLocation> allHarbour = referentialService.getAllHarbour(); + Assert.assertNotNull(allHarbour); + Assert.assertTrue(allHarbour.size() > 1); + cruise.setDepartureLocation(allHarbour.get(0)); + cruise.setReturnLocation(allHarbour.get(1)); + + 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((String) 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((String) 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 createAndSaveBenthosBatchAndFrequencies() { + SpeciesBatch esp1Batch; + SpeciesBatch esp2Batch; + SpeciesBatch frequenciesParentBatch; + SpeciesBatch batch; + 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); + + assertCreateAndReloadBenthosBatch(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((String) 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); + + assertCreateAndReloadBenthosBatch(batch, batch.getParentBatch().getId()); + + // ----------------------------------------------------------------------------- + // 3. Test child "Female/2" + // ----------------------------------------------------------------------------- + // Batch : ESP1 - Vrac/5 Female/3 Nombre/14 + batch = new SpeciesBatch(); + batch.setId((String) 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); + + assertCreateAndReloadBenthosBatch(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); + + assertCreateAndReloadBenthosBatch(batch, null); + esp2Batch = batch; + + // Batch : ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11 + batch = new SpeciesBatch(); + batch.setId((String) 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); + + assertCreateAndReloadBenthosBatch(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.saveBenthosBatch(batch); + assertSpeciesBatch(savedBatch, batch, false); + SpeciesBatch reloadedBatch = getBenthosBatch(fishingOperationWithEmptyBatch.getId(), savedBatch.getId()); + assertSpeciesBatch(savedBatch, reloadedBatch, true); + + // Save batch for later + frequenciesParentBatch = batch; + + // ----------------------------------------------------------------------------- + // 6. Test change species + // ----------------------------------------------------------------------------- + esp2Batch.setSpecies(taxon1); + service.changeBenthosBatchSpecies(esp2Batch.getId(), taxon1); + assertSpeciesBatch(savedBatch, batch, false); + reloadedBatch = getBenthosBatch(fishingOperationWithEmptyBatch.getId(), esp2Batch.getId()); + assertSpeciesBatch(esp2Batch, reloadedBatch, true); + + // ----------------------------------------------------------------------------- + // 7. Test get all root species + // ----------------------------------------------------------------------------- + List<SpeciesBatch> rootSpeciesBatch = service.getRootBenthosBatch(fishingOperationWithEmptyBatch.getId()).getChildren(); + 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 = assertCreateAndReloadBenthosBatchFrequency(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) + // Note: use a new list (everything list coming from service are not modifiable) + createdFrequencies = Lists.newArrayList(createdFrequencies); + createdFrequencies.remove(createdFrequencies.size() - 1); + + List<SpeciesBatchFrequency> savedFrequencies = service.saveBenthosBatchFrequency(frequenciesParentBatch.getId(), createdFrequencies); + assertBatchFrequencies(createdFrequencies, savedFrequencies, true); + } + + @Test + public void deleteBenthosBatch(/* 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); + assertCreateAndReloadBenthosBatch(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); + assertCreateAndReloadBenthosBatch(batch, esp1Batch.getId()); + + // Try to remove + service.deleteBenthosBatch(esp1Batch.getId()); + + // Check if remove + try { + batch = getBenthosBatch(fishingOperationWithEmptyBatch.getId(), esp1Batch.getId()); + assertNull(batch); + } catch (DataRetrievalFailureException drfe) { + assertNotNull(drfe); + } + } + + protected void assertCreateAndReloadBenthosBatch(SpeciesBatch batch, String parentBatchId) { + batch.setFishingOperation(fishingOperationWithEmptyBatch); + + // Create batch + SpeciesBatch createdBatch = service.createBenthosBatch(batch, parentBatchId); + assertSpeciesBatch(batch, createdBatch, false); + + // then reload (for round trip check) + SpeciesBatch reloadedBatch = getBenthosBatch(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 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> assertCreateAndReloadBenthosBatchFrequency(List<SpeciesBatchFrequency> frequencies, String parentBatchId) { + + // Create batch + List<SpeciesBatchFrequency> createdFrequencies = service.saveBenthosBatchFrequency(parentBatchId, frequencies); + assertBatchFrequencies(frequencies, createdFrequencies, false); + + // then reload (for round trip check) + List<SpeciesBatchFrequency> reloadedFrequencies = service.getAllBenthosBatchFrequency(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 getBenthosBatch(String fishingOperationId, String speciesBatchId) { + return getSpeciesBatch(speciesBatchId, service.getRootBenthosBatch(fishingOperationId).getChildren()); + } + + 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/BenthosBatchPersistenceServiceWriteTest.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Added: svn:eol-style + native Copied: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceReadTest.java (from rev 684, trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java) =================================================================== --- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceReadTest.java (rev 0) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceReadTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,77 @@ +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.adagio.core.dao.data.batch.validator.CatchBatchValidationException; +import fr.ifremer.tutti.persistence.DatabaseResource; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * To test {@link CatchBatchPersistenceService} for read operation. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +public class CatchBatchPersistenceServiceReadTest { + + @ClassRule + public static final DatabaseResource dbResource = DatabaseResource.writeDb(); + + protected CatchBatchPersistenceService service; + + protected FishingOperationPersistenceService fishingOperationService; + + protected FishingOperation fishingOperation; + + @Before + public void setUp() throws Exception { + service = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService(); + 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(expected = CatchBatchValidationException.class) + public void getCatchBatchFromFishingOperation() throws Exception { + + //TODO-TC Change test when data will be Tutti-aware + // old CGFS tree structure is still not valid + service.getCatchBatchFromFishingOperation(fishingOperation.getId()); + } + +} Copied: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceWriteTest.java (from rev 684, trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java) =================================================================== --- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceWriteTest.java (rev 0) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceWriteTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,323 @@ +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.adagio.core.dao.data.batch.validator.CatchBatchValidationException; +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.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.entities.referential.TuttiLocation; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * To test {@link CatchBatchPersistenceService} for write operation. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +public class CatchBatchPersistenceServiceWriteTest { + + @ClassRule + public static final DatabaseResource dbResource = DatabaseResource.writeDb(); + + protected CatchBatchPersistenceService service; + + protected CruisePersistenceService cruiseService; + + protected FishingOperationPersistenceService fishingOperationService; + + protected ReferentialPersistenceService referentialService; + + /* + * Entities prepared in setUp() : + * */ + 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.getCatchBatchPersistenceService(); + cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService(); + fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService(); + referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService(); + + species = referentialService.getAllSpecies(); + assertNotNull(species); + assertTrue(species.size() > 2); + + cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId()); + cruise.setId((String) null); + Calendar calendar = new GregorianCalendar(); + cruise.setBeginDate(calendar.getTime()); + calendar.add(Calendar.MONTH, 1); // add one month + cruise.setEndDate(calendar.getTime()); + List<TuttiLocation> allHarbour = referentialService.getAllHarbour(); + Assert.assertNotNull(allHarbour); + Assert.assertTrue(allHarbour.size() > 1); + cruise.setDepartureLocation(allHarbour.get(0)); + cruise.setReturnLocation(allHarbour.get(1)); + + 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((String) 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((String) 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 = service.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((String) 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); + } + + // Benthos + { + catchBatch.setBenthosTotalSortedWeight(24f); + catchBatch.setBenthosTotalSampleSortedWeight(16f); + catchBatch.setBenthosTotalLivingNotItemizedWeight(0.4f); + catchBatch.setBenthosTotalInertWeight(0.2f); + } + } + // Hors Vrac : 10kg + { + catchBatch.setCatchTotalUnsortedWeight(10f); + + // Species + { + catchBatch.setSpeciesTotalUnsortedWeight(10f); + } + // Benthos + { + catchBatch.setBenthosTotalUnsortedWeight(20f); + } + } + // 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()); + } + + protected void assertCreateAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) { + CatchBatch createdCatchBatch = service.createCatchBatch(catchBatch); + assertNotNull(createdCatchBatch); + assertNotNull(createdCatchBatch.getId()); + assertCatchBatch(catchBatch, createdCatchBatch, false); + + CatchBatch reloadedCatchBatch = null; + try { + reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId); + } catch (CatchBatchValidationException e) { + Assert.fail(e.getMessage()); + } + 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 = null; + try { + reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId); + } catch (CatchBatchValidationException e) { + Assert.fail(e.getMessage()); + } + 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()); + + assertEquals(expectedCatchBatch.getBenthosTotalSampleSortedWeight(), actualCatchBatch.getBenthosTotalSampleSortedWeight()); + assertEquals(expectedCatchBatch.getBenthosTotalSortedWeight(), actualCatchBatch.getBenthosTotalSortedWeight()); + assertEquals(expectedCatchBatch.getBenthosTotalUnsortedWeight(), actualCatchBatch.getBenthosTotalUnsortedWeight()); + assertEquals(expectedCatchBatch.getBenthosTotalInertWeight(), actualCatchBatch.getBenthosTotalInertWeight()); + assertEquals(expectedCatchBatch.getBenthosTotalLivingNotItemizedWeight(), actualCatchBatch.getBenthosTotalLivingNotItemizedWeight()); + } +} Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceWriteTest.java =================================================================== --- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceWriteTest.java 2013-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceWriteTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -82,7 +82,7 @@ // ----------------------------------------------------------------------------- // 1. Test with all properties filled // ----------------------------------------------------------------------------- - cruise.setId(null); + cruise.setId((String)null); cruise.setName("Unit-test-" + System.currentTimeMillis()); @@ -148,7 +148,7 @@ // ----------------------------------------------------------------------------- // 2. Test with only mandatory properties // ----------------------------------------------------------------------------- - createdCruise.setId(null); + createdCruise.setId((String)null); createdCruise.setHeadOfMission(null); // createdCruise.setBeginDate(cruise.getBeginDate()); // createdCruise.setEndDate(cruise.getEndDate()); @@ -203,7 +203,7 @@ // ----------------------------------------------------------------------------- Cruise cruise = service.getCruise(dbResource.getFixtures().cruiseId()); - cruise.setId(null); + cruise.setId((String)null); Calendar calendar = new GregorianCalendar(); cruise.setBeginDate(calendar.getTime()); Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceWriteTest.java =================================================================== --- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceWriteTest.java 2013-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceWriteTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -87,7 +87,7 @@ // Duplicate an existing cruise, to attach new fishing operations cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId()); - cruise.setId(null); + cruise.setId((String)null); cruise.setName("Unit-test-" + System.currentTimeMillis()); Calendar calendar = new GregorianCalendar(); cruise.setBeginDate(calendar.getTime()); @@ -206,7 +206,7 @@ // 2. Test with all properties set // ----------------------------------------------------------------------------- // Set properties - fishingOperation.setId(null); + fishingOperation.setId((String)null); fishingOperation.setStationNumber("STA2"); fishingOperation.setFishingOperationNumber(2); fishingOperation.setMultirigAggregation("1"); @@ -319,7 +319,7 @@ // - try to save a operation using a gear not declared in the cruise // - try to save a operation using a multirig aggregation greater than the cruise multirig number // ----------------------------------------------------------------------------- - fishingOperation.setId(null); + fishingOperation.setId((String)null); // Find and set a gear not used in the cruise List<Gear> gears = referentialService.getAllFishingGear(); Copied: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceReadTest.java (from rev 684, trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java) =================================================================== --- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceReadTest.java (rev 0) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceReadTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,193 @@ +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.collect.Maps; +import fr.ifremer.tutti.persistence.DatabaseResource; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +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 java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * To test {@link SpeciesBatchPersistenceService} for read operation. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +@Ignore +public class SpeciesBatchPersistenceServiceReadTest { + + @ClassRule + public static final DatabaseResource dbResource = DatabaseResource.writeDb(); + + protected SpeciesBatchPersistenceService service; + + protected FishingOperationPersistenceService fishingOperationService; + + protected FishingOperation fishingOperation; + + @Before + public void setUp() throws Exception { + service = TuttiPersistenceServiceLocator.getSpeciesBatchPersistenceService(); + 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()); + } + + @Ignore + @Test + public void getRootSpeciesBatch(/*String fishingOperationId*/) { + //TODO Do me! + service.getRootSpeciesBatch(fishingOperation.getId()); + } + + @Ignore + @Test + public void getAllSpeciesBatchFrequency(/*String speciesBatchId*/) { + //TODO Do me! + } + + @Ignore + @Test + public void getRootBenthosBatch(/*String fishingOperationId*/) { + //TODO Do me! + } + + + 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 SpeciesBatch getSpeciesBatch(String fishingOperationId, + String speciesBatchId) { + BatchContainer<SpeciesBatch> rootSpeciesBatch = service.getRootSpeciesBatch(fishingOperationId); + return getSpeciesBatch(speciesBatchId, rootSpeciesBatch.getChildren()); + } + + 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; + } + +} Copied: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceWriteTest.java (from rev 684, trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java) =================================================================== --- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceWriteTest.java (rev 0) +++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceWriteTest.java 2013-03-27 21:49:05 UTC (rev 693) @@ -0,0 +1,534 @@ +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.collect.Lists; +import com.google.common.collect.Maps; +import fr.ifremer.tutti.persistence.DatabaseResource; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +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 fr.ifremer.tutti.persistence.entities.referential.TuttiLocation; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.springframework.dao.DataRetrievalFailureException; + +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.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * To test {@link SpeciesBatchPersistenceService} for write operation. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +public class SpeciesBatchPersistenceServiceWriteTest { + + @ClassRule + public static final DatabaseResource dbResource = DatabaseResource.writeDb(); + + protected SpeciesBatchPersistenceService service; + + protected CatchBatchPersistenceService catchBatchService; + + protected CruisePersistenceService cruiseService; + + protected FishingOperationPersistenceService fishingOperationService; + + protected ReferentialPersistenceService referentialService; + + /* + * Entities prepared in setUp() : + * */ + 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.getSpeciesBatchPersistenceService(); + cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService(); + catchBatchService = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService(); + fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService(); + referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService(); + + species = referentialService.getAllSpecies(); + assertNotNull(species); + assertTrue(species.size() > 2); + + cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId()); + cruise.setId((String) null); + Calendar calendar = new GregorianCalendar(); + cruise.setBeginDate(calendar.getTime()); + calendar.add(Calendar.MONTH, 1); // add one month + cruise.setEndDate(calendar.getTime()); + List<TuttiLocation> allHarbour = referentialService.getAllHarbour(); + Assert.assertNotNull(allHarbour); + Assert.assertTrue(allHarbour.size() > 1); + cruise.setDepartureLocation(allHarbour.get(0)); + cruise.setReturnLocation(allHarbour.get(1)); + + 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((String) 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((String) 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 createAndSaveSpeciesBatchAndFrequencies() { + SpeciesBatch esp1Batch; + SpeciesBatch esp2Batch; + SpeciesBatch frequenciesParentBatch; + SpeciesBatch batch; + 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((String) 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((String) 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((String) 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 + // ----------------------------------------------------------------------------- + BatchContainer<SpeciesBatch> rootSpeciesBatc = service.getRootSpeciesBatch(fishingOperationWithEmptyBatch.getId()); + List<SpeciesBatch> rootSpeciesBatch = rootSpeciesBatc.getChildren(); + 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) + // Note: use a new list (everything list coming from service are not modifiable) + createdFrequencies = Lists.newArrayList(createdFrequencies); + createdFrequencies.remove(createdFrequencies.size() - 1); + + List<SpeciesBatchFrequency> savedFrequencies = service.saveSpeciesBatchFrequency(frequenciesParentBatch.getId(), createdFrequencies); + 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 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.getRootSpeciesBatch(fishingOperationId).getChildren()); + } + + 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; + } +} Modified: trunk/tutti-persistence/src/test/resources/log4j.properties =================================================================== --- trunk/tutti-persistence/src/test/resources/log4j.properties 2013-03-27 21:44:37 UTC (rev 692) +++ trunk/tutti-persistence/src/test/resources/log4j.properties 2013-03-27 21:49:05 UTC (rev 693) @@ -37,6 +37,6 @@ #log4j.logger.net.sf.ehcache=WARN -log4j.logger.fr.ifremer.adagio.core=DEBUG +log4j.logger.fr.ifremer.adagio.core=ERROR log4j.logger.fr.ifremer.tutti=INFO #log4j.logger.org.nuiton=INFO
participants (1)
-
tchemit@users.forge.codelutin.com