Author: tchemit Date: 2013-09-28 14:15:25 +0200 (Sat, 28 Sep 2013) New Revision: 1247 Url: http://forge.codelutin.com/projects/tutti/repository/revisions/1247 Log: - refacctor service names - move selected protocol inside the persistence layer (to make transparent call with protocol embedded in persistence layer) - fixes #3330: [CAPTURE] gestion des poids dans le tableau Added: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/WeightUnit.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightCleaningService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightComputingService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/MultiPostExportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/MultiPostImportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/ProtocolImportExportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/PupitriImportExportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/ReferentialImportExportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/CatchesSumatraExportService.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/WeightComputingServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/MultiPostExportServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/ProtocolImportExportServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/PupitriImportExportServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/ReferentialImportExportServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/CatchesSumatraExportServiceTest.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/service/ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/CleanBatchWeightsAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeBatchWeightsAction.java Removed: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostImportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportService.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportServiceTest.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportServiceTest.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/WeightUnit.java Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistence.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceImpl.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceNoDbImpl.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/protocol/TuttiProtocols.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/IndividualObservationBatchPersistenceServiceImpl.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ProtocolPersistenceService.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ProtocolPersistenceServiceImpl.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java trunk/tutti-persistence/src/main/xmi/tutti-persistence.zargo trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/PersistenceService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/TuttiDataContext.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/TuttiServiceContext.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/ExportCatchesReportService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/ValidateCruiseOperationsService.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/config/TuttiServiceConfig.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/config/TuttiServiceConfigOption.java trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/export/TuttiExportService.java trunk/tutti-service/src/main/resources/i18n/tutti-service_en_GB.properties trunk/tutti-service/src/main/resources/i18n/tutti-service_fr_FR.properties trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/ServiceDbResource.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/export/TuttiExportService2Test.java trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/export/TuttiExportServiceTest.java trunk/tutti-ui-swing/src/main/filtered-resources/tutti-help-en.properties trunk/tutti-ui-swing/src/main/filtered-resources/tutti-help-fr.properties trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUIContext.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/config/TuttiApplicationConfig.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/config/TuttiApplicationConfigOption.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/config/TuttiConfigUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportCruiseAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportCruiseForSumatraAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportProgramAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportProtocolAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ImportProtocolAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/SelectCruiseUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/AbstractExportMultiPostAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/AbstractImportMultiPostAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.css trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.jaxx trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUIModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/SampleCategoryComponent.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchRowModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchTableModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchRowModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchTableModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/CreateBenthosMelagAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/ImportMultiPostAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/create/CreateBenthosBatchUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyRowModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyTableModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyUIModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/split/SplitBenthosBatchUIModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchRowModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchTableModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/create/CreateIndividualObservationBatchUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/ImportMultiPostAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchRowModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchTableModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/CreateSpeciesMelagAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/ImportMultiPostAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/ImportPupitriAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchRowModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchTableModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/create/CreateSpeciesBatchUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyRowModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyTableModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/SplitSpeciesBatchUIModel.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/AbstractCaracteristicTabUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/GearUseFeatureTabUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/VesselUseFeatureTabUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportAllCaracteristicAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolBenthosAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolCaracteristicAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolSpeciesAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportPupitriAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolBenthosAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolCaracteristicAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolSpeciesAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryGearExampleAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryPersonExampleAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporarySpeciesExampleAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryVesselExampleAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryGearAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryPersonAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporarySpeciesAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryVesselAction.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/AbstractTuttiUIHandler.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/TuttiUI.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataTableCell.java trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/species/EnterMelagWeightDialog.jaxx trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_en_GB.properties trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties trunk/tutti-ui-swing/src/test/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyRowModelTest.java Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistence.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistence.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistence.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -183,44 +183,24 @@ List<Vessel> getAllFishingVessel(); /** - * Get all species (referent or synonym) with no {@link Species#getSurveyCode()} - * filled. + * Get all species (referent or synonym) with with {@link Species#getSurveyCode()} + * filled by optional protocol. * - * @return all species with no {@code surveyCode} filled at all. + * @return all species with {@code surveyCode} filled if possible. * @since 0.1 */ List<Species> getAllSpecies(); /** - * Get all {@code referent} species with no {@link Species#getSurveyCode()} - * filled. + * Get all {@code referent} species with {@link Species#getSurveyCode()} + * filled by optional protocol. * - * @return all species with no {@code surveyCode} filled at all. + * @return all species with {@code surveyCode} filled if possible. * @since 1.0 */ List<Species> getAllReferentSpecies(); /** - * Get all species (referent or synonym) with {@link Species#getSurveyCode()} - * filled by optional protocol. - * - * @param protocol optional protocol to fill some species cruisecode. - * @return all species with {@code surveyCode} filled for species definied in protocol. - * @since 1.0 - */ - List<Species> getAllSpecies(TuttiProtocol protocol); - - /** - * Get all {@code referent} species with no {@link Species#getSurveyCode()} - * filled by optional protocol. - * - * @param protocol optional protocol to fill some species cruisecode. - * @return all species with no {@code surveyCode} filled at all. - * @since 1.1 - */ - List<Species> getAllReferentSpecies(TuttiProtocol protocol); - - /** * Obtain a species with external code as vernacular code given his referenceTaxonId. * <p/> * <strong>Note:</strong> {@link Species#getRefTaxCode()} will not be @@ -280,10 +260,6 @@ Caracteristic getDeadOrAliveCaracteristic(); -// Caracteristic getSampleIdCaracteristic(); -// -// Caracteristic getOtolitheIdCaracteristic(); - Caracteristic getPmfmIdCaracteristic(); Caracteristic getWeightMeasuredCaracteristic(); @@ -454,6 +430,24 @@ //-- Protocol methods --// //------------------------------------------------------------------------// + /** + * The protocol used by the persistence lay (used to consolidate entites). + * + * @return The protocol used by the persistence layer + * @see #setProtocol(TuttiProtocol) + * @since 2.6 + */ + TuttiProtocol getProtocol(); + + /** + * Set the protocol to use by the persistence layer. + * + * @param protocol the new protocol to use (can be null) + * @see #getProtocol() + * @since 2.6 + */ + void setProtocol(TuttiProtocol protocol); + List<String> getAllProtocolNames(); List<TuttiProtocol> getAllProtocol(); 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-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceImpl.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -301,25 +301,15 @@ @Override public List<Species> getAllSpecies() { - return referentialService.getAllSpecies(); - } - - @Override - public List<Species> getAllReferentSpecies() { - return referentialService.getAllReferentSpecies(); - } - - @Override - public List<Species> getAllSpecies(TuttiProtocol protocol) { List<Species> result = referentialService.getAllSpecies(); - setSpeciesSurveyCode(result, protocol); + setSpeciesSurveyCode(result, getProtocol()); return result; } @Override - public List<Species> getAllReferentSpecies(TuttiProtocol protocol) { + public List<Species> getAllReferentSpecies() { List<Species> result = referentialService.getAllReferentSpecies(); - setSpeciesSurveyCode(result, protocol); + setSpeciesSurveyCode(result, getProtocol()); return result; } @@ -328,27 +318,6 @@ return referentialService.getSpeciesByReferenceTaxonIdWithVernacularCode(referenceTaxonId); } - protected void setSpeciesSurveyCode(List<Species> speciesList, TuttiProtocol protocol) { - if (protocol != null && !protocol.isSpeciesEmpty()) { - - Map<Integer, String> surveyCodeByTaxonId = Maps.newTreeMap(); - - for (SpeciesProtocol speciesProtocol : protocol.getSpecies()) { - String surveyCode = speciesProtocol.getSpeciesSurveyCode(); - if (StringUtils.isNotBlank(surveyCode)) { - Integer taxonId = - speciesProtocol.getSpeciesReferenceTaxonId(); - surveyCodeByTaxonId.put(taxonId, surveyCode); - } - } - for (Species species : speciesList) { - Integer taxonId = species.getReferenceTaxonId(); - String surveyCode = surveyCodeByTaxonId.get(taxonId); - species.setSurveyCode(surveyCode); - } - } - } - @Override public List<Caracteristic> getAllCaracteristic() { return referentialService.getAllCaracteristic(); @@ -429,16 +398,6 @@ return referentialService.getDeadOrAliveCaracteristic(); } -// @Override -// public Caracteristic getSampleIdCaracteristic() { -// return referentialService.getSampleIdCaracteristic(); -// } -// -// @Override -// public Caracteristic getOtolitheIdCaracteristic() { -// return referentialService.getOtolitheIdCaracteristic(); -// } - @Override public Caracteristic getPmfmIdCaracteristic() { return referentialService.getPmfmIdCaracteristic(); @@ -617,6 +576,16 @@ //------------------------------------------------------------------------// @Override + public TuttiProtocol getProtocol() { + return protocolService.getProtocol(); + } + + @Override + public void setProtocol(TuttiProtocol protocol) { + protocolService.setProtocol(protocol); + } + + @Override public boolean isProtocolExist(String id) { return protocolService.isProtocolExist(id); } @@ -651,7 +620,6 @@ return protocolService.getProtocol(id); } - //------------------------------------------------------------------------// //-- Fishing operation methods --// //------------------------------------------------------------------------// @@ -870,4 +838,29 @@ public void deleteIndividualObservationBatch(String id) { individualObservationBatchService.deleteIndividualObservationBatch(id); } + + //------------------------------------------------------------------------// + //-- Internal methods --// + //------------------------------------------------------------------------// + + protected void setSpeciesSurveyCode(List<Species> speciesList, TuttiProtocol protocol) { + if (protocol != null && !protocol.isSpeciesEmpty()) { + + Map<Integer, String> surveyCodeByTaxonId = Maps.newTreeMap(); + + for (SpeciesProtocol speciesProtocol : protocol.getSpecies()) { + String surveyCode = speciesProtocol.getSpeciesSurveyCode(); + if (StringUtils.isNotBlank(surveyCode)) { + Integer taxonId = + speciesProtocol.getSpeciesReferenceTaxonId(); + surveyCodeByTaxonId.put(taxonId, surveyCode); + } + } + for (Species species : speciesList) { + Integer taxonId = species.getReferenceTaxonId(); + String surveyCode = surveyCodeByTaxonId.get(taxonId); + species.setSurveyCode(surveyCode); + } + } + } } Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceNoDbImpl.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceNoDbImpl.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/TuttiPersistenceNoDbImpl.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -160,16 +160,6 @@ } @Override - public List<Species> getAllSpecies(TuttiProtocol protocol) { - throw notImplemented(); - } - - @Override - public List<Species> getAllReferentSpecies(TuttiProtocol protocol) { - throw notImplemented(); - } - - @Override public Species getSpeciesByReferenceTaxonIdWithVernacularCode(Integer referenceTaxonId) { throw notImplemented(); } @@ -249,16 +239,6 @@ throw notImplemented(); } -// @Override -// public Caracteristic getSampleIdCaracteristic() { -// throw notImplemented(); -// } -// -// @Override -// public Caracteristic getOtolitheIdCaracteristic() { -// throw notImplemented(); -// } - @Override public Caracteristic getPmfmIdCaracteristic() { throw notImplemented(); @@ -390,6 +370,16 @@ } @Override + public TuttiProtocol getProtocol() { + throw notImplemented(); + } + + @Override + public void setProtocol(TuttiProtocol protocol) { + throw notImplemented(); + } + + @Override public List<String> getAllProtocolNames() { throw notImplemented(); } Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/protocol/TuttiProtocols.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/protocol/TuttiProtocols.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/protocol/TuttiProtocols.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -34,11 +34,7 @@ import fr.ifremer.tutti.TuttiTechnicalException; import fr.ifremer.tutti.persistence.TuttiPersistence; import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatchFrequency; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; import fr.ifremer.tutti.persistence.entities.protocol.v1.SpeciesProtocol1; import fr.ifremer.tutti.persistence.entities.protocol.v1.SpeciesProtocolBean1; import fr.ifremer.tutti.persistence.entities.protocol.v1.TuttiProtocol1; @@ -291,79 +287,79 @@ return result; } - /** - * Is the species batch respecting the protocol recommendations? - * - * @param protocol the current protocol - * @param batch the batch to check (it should be a leaf) - * @param frequencies the frequencies of the batch - * @return true if the batch respects the protocol, false otherwise - */ - public static boolean isSpeciesBatchValid(TuttiProtocol protocol, - SpeciesBatch batch, - List<SpeciesBatchFrequency> frequencies) { - boolean result = true; +// /** +// * Is the species batch respecting the protocol recommendations? +// * +// * @param protocol the current protocol +// * @param batch the batch to check (it should be a leaf) +// * @param frequencies the frequencies of the batch +// * @return true if the batch respects the protocol, false otherwise +// */ +// public static boolean isSpeciesBatchValid(TuttiProtocol protocol, +// SpeciesBatch batch, +// List<SpeciesBatchFrequency> frequencies) { +// boolean result = true; +// +// if (protocol != null) { +// Species species = batch.getSpecies(); +// List<SpeciesProtocol> speciesProtocols = protocol.getSpecies(); +// SpeciesProtocol speciesProtocol = getSpeciesProtocol(species, speciesProtocols); +// +// if (speciesProtocol != null) { +// List<Integer> mandatoryCategories = speciesProtocol.getMandatorySampleCategoryId(); +// +// SpeciesBatch browsingBatch = batch; +// while (browsingBatch.getParentBatch() != null) { +// mandatoryCategories.remove(browsingBatch.getSampleCategoryId()); +// browsingBatch = browsingBatch.getParentBatch(); +// } +// result = mandatoryCategories.isEmpty() && +// (!speciesProtocol.isCountIfNoFrequencyEnabled() +// || CollectionUtils.isNotEmpty(frequencies) +// || batch.getNumber() != null); +// } +// } +// return result; +// } - if (protocol != null) { - Species species = batch.getSpecies(); - List<SpeciesProtocol> speciesProtocols = protocol.getSpecies(); - SpeciesProtocol speciesProtocol = getSpeciesProtocol(species, speciesProtocols); +// /** +// * Is the benthos batch respecting the protocol recommendations? +// * +// * @param protocol the current protocol +// * @param batch the batch to check (it should be a leaf) +// * @param frequencies the frequencies of the batch +// * @return true if the batch respects the protocol, false otherwise +// */ +// public static boolean isBenthosBatchValid(TuttiProtocol protocol, +// BenthosBatch batch, +// List<BenthosBatchFrequency> frequencies) { +// boolean result = true; +// +// if (protocol != null) { +// Species species = batch.getSpecies(); +// List<SpeciesProtocol> speciesProtocols = protocol.getBenthos(); +// SpeciesProtocol speciesProtocol = getSpeciesProtocol(species, speciesProtocols); +// +// if (speciesProtocol != null) { +// // get the categories which should be set +// List<Integer> mandatoryCategories = +// speciesProtocol.getMandatorySampleCategoryId(); +// +// BenthosBatch browsingBatch = batch; +// while (browsingBatch.getParentBatch() != null) { +// mandatoryCategories.remove(browsingBatch.getSampleCategoryId()); +// browsingBatch = browsingBatch.getParentBatch(); +// } +// result = mandatoryCategories.isEmpty() && +// (!speciesProtocol.isCountIfNoFrequencyEnabled() +// || CollectionUtils.isNotEmpty(frequencies) +// || batch.getNumber() != null); +// } +// } +// return result; +// } - if (speciesProtocol != null) { - List<Integer> mandatoryCategories = speciesProtocol.getMandatorySampleCategoryId(); - - SpeciesBatch browsingBatch = batch; - while (browsingBatch.getParentBatch() != null) { - mandatoryCategories.remove(browsingBatch.getSampleCategoryId()); - browsingBatch = browsingBatch.getParentBatch(); - } - result = mandatoryCategories.isEmpty() && - (!speciesProtocol.isCountIfNoFrequencyEnabled() - || CollectionUtils.isNotEmpty(frequencies) - || batch.getNumber() != null); - } - } - return result; - } - /** - * Is the benthos batch respecting the protocol recommendations? - * - * @param protocol the current protocol - * @param batch the batch to check (it should be a leaf) - * @param frequencies the frequencies of the batch - * @return true if the batch respects the protocol, false otherwise - */ - public static boolean isBenthosBatchValid(TuttiProtocol protocol, - BenthosBatch batch, - List<BenthosBatchFrequency> frequencies) { - boolean result = true; - - if (protocol != null) { - Species species = batch.getSpecies(); - List<SpeciesProtocol> speciesProtocols = protocol.getBenthos(); - SpeciesProtocol speciesProtocol = getSpeciesProtocol(species, speciesProtocols); - - if (speciesProtocol != null) { - // get the categories which should be set - List<Integer> mandatoryCategories = - speciesProtocol.getMandatorySampleCategoryId(); - - BenthosBatch browsingBatch = batch; - while (browsingBatch.getParentBatch() != null) { - mandatoryCategories.remove(browsingBatch.getSampleCategoryId()); - browsingBatch = browsingBatch.getParentBatch(); - } - result = mandatoryCategories.isEmpty() && - (!speciesProtocol.isCountIfNoFrequencyEnabled() - || CollectionUtils.isNotEmpty(frequencies) - || batch.getNumber() != null); - } - } - return result; - } - - /** * Retrieve the speciesProtocol corresponding to the species of the given protocol. * * @param protocol @@ -375,17 +371,17 @@ return getSpeciesProtocol(species, protocol.getSpecies()); } - /** - * Retrieve the benthosProtocol corresponding to the species of the given protocol. - * - * @param protocol - * @param species - * @return - * @since 2.5 - */ - public static SpeciesProtocol getBenthosProtocol(TuttiProtocol protocol, Species species) { - return getSpeciesProtocol(species, protocol.getBenthos()); - } +// /** +// * Retrieve the benthosProtocol corresponding to the species of the given protocol. +// * +// * @param protocol +// * @param species +// * @return +// * @since 2.5 +// */ +// public static SpeciesProtocol getBenthosProtocol(TuttiProtocol protocol, Species species) { +// return getSpeciesProtocol(species, protocol.getBenthos()); +// } /** * Retrieve the speciesprotocol corresponding to the species of the batch @@ -394,8 +390,8 @@ * @param speciesProtocols * @return */ - protected static SpeciesProtocol getSpeciesProtocol(Species species, - List<SpeciesProtocol> speciesProtocols) { + public static SpeciesProtocol getSpeciesProtocol(Species species, + List<SpeciesProtocol> speciesProtocols) { for (SpeciesProtocol speciesProtocol : speciesProtocols) { if (species.getReferenceTaxonId().equals( speciesProtocol.getSpeciesReferenceTaxonId())) { Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/IndividualObservationBatchPersistenceServiceImpl.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/IndividualObservationBatchPersistenceServiceImpl.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/IndividualObservationBatchPersistenceServiceImpl.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -284,20 +284,6 @@ CaracteristicMap caracteristics = CaracteristicMap.copy(source.getCaracteristics()); -// if (source.getSamplingCode() != null) { -// -// Caracteristic caracteristic = -// referentialService.getSampleIdCaracteristic(); -// caracteristics.put(caracteristic, source.getSamplingCode()); -// } -// -// if (source.getCalcifiedPieceSamplingCode() != null) { -// -// Caracteristic caracteristic = -// referentialService.getOtolitheIdCaracteristic(); -// caracteristics.put(caracteristic, source.getCalcifiedPieceSamplingCode()); -// } - if (source.getWeight() != null) { Caracteristic caracteristic = referentialService.getWeightMeasuredCaracteristic(); @@ -332,16 +318,6 @@ samplePersistenceHelper.fillSampleMeasurements( result, batch.getIdAsInt()); -// String sampleCode = (String) result.remove(referentialService.getSampleIdCaracteristic()); -// if (sampleCode != null) { -// batch.setSamplingCode(sampleCode); -// } -// -// String calcifiedPieceSampleCode = (String) result.remove(referentialService.getOtolitheIdCaracteristic()); -// if (sampleCode != null) { -// batch.setCalcifiedPieceSamplingCode(calcifiedPieceSampleCode); -// } - Float weight = (Float) result.remove(referentialService.getWeightMeasuredCaracteristic()); if (weight != null) { batch.setWeight(weight); Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ProtocolPersistenceService.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ProtocolPersistenceService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ProtocolPersistenceService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -35,9 +35,12 @@ * @author tchemit <chemit@codelutin.com> * @since 0.3 */ -//@Transactional(readOnly = true) public interface ProtocolPersistenceService extends TuttiPersistenceServiceImplementor { + TuttiProtocol getProtocol(); + + void setProtocol(TuttiProtocol protocol); + boolean isProtocolExist(String id); List<String> getAllProtocolId(); Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ProtocolPersistenceServiceImpl.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ProtocolPersistenceServiceImpl.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ProtocolPersistenceServiceImpl.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -59,6 +59,16 @@ public static final String TUTTI_PROTOCOL_EXTENSION = "tuttiProtocol"; + public static TuttiProtocol sharedProtocol; + + public TuttiProtocol getProtocol() { + return sharedProtocol; + } + + public void setProtocol(TuttiProtocol protocol) { + sharedProtocol = protocol; + } + @Override public boolean isProtocolExist(String id) { return getAllProtocolId().contains(id); Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -245,10 +245,6 @@ Caracteristic getDeadOrAliveCaracteristic(); -// Caracteristic getSampleIdCaracteristic(); -// -// Caracteristic getOtolitheIdCaracteristic(); - Caracteristic getPmfmIdCaracteristic(); Caracteristic getWeightMeasuredCaracteristic(); Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java =================================================================== --- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -626,20 +626,6 @@ return result; } -// @Override -// public Caracteristic getSampleIdCaracteristic() { -// Integer pmfmId = enumeration.PMFM_ID_SAMPLE_ID; -// Caracteristic result = thisService.getCaracteristic(pmfmId); -// return result; -// } -// -// @Override -// public Caracteristic getOtolitheIdCaracteristic() { -// Integer pmfmId = enumeration.PMFM_ID_OTOLITHE_ID; -// Caracteristic result = thisService.getCaracteristic(pmfmId); -// return result; -// } - @Override public Caracteristic getPmfmIdCaracteristic() { Integer pmfmId = enumeration.PMFM_ID_ID_PSFM; Modified: trunk/tutti-persistence/src/main/xmi/tutti-persistence.zargo =================================================================== (Binary files differ) Modified: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/PersistenceService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/PersistenceService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/PersistenceService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -24,13 +24,17 @@ * #L% */ +import com.google.common.base.Function; import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import fr.ifremer.tutti.TuttiBusinessException; import fr.ifremer.tutti.TuttiIOUtil; import fr.ifremer.tutti.persistence.InvalidBatchModelException; import fr.ifremer.tutti.persistence.TuttiPersistence; import fr.ifremer.tutti.persistence.TuttiPersistenceNoDbImpl; import fr.ifremer.tutti.persistence.config.TuttiPersistenceConfig; +import fr.ifremer.tutti.persistence.entities.TuttiEntities; import fr.ifremer.tutti.persistence.entities.data.AccidentalBatch; import fr.ifremer.tutti.persistence.entities.data.AttachementObjectTypeEnum; import fr.ifremer.tutti.persistence.entities.data.Attachment; @@ -44,8 +48,11 @@ import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; import fr.ifremer.tutti.persistence.entities.data.Program; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; +import fr.ifremer.tutti.persistence.entities.data.SpeciesAbleBatch; +import fr.ifremer.tutti.persistence.entities.data.SpeciesAbleBatchFrequency; import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; +import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.Gear; @@ -58,6 +65,7 @@ import fr.ifremer.tutti.persistence.service.TuttiEnumerationFile; import fr.ifremer.tutti.persistence.service.TuttiPersistenceServiceLocator; import fr.ifremer.tutti.service.config.TuttiServiceConfig; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.logging.Log; @@ -70,7 +78,9 @@ import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.concurrent.Callable; import static org.nuiton.i18n.I18n._; @@ -95,6 +105,69 @@ init(); } + public static interface FrequencyFunction<S extends SpeciesAbleBatch, F extends SpeciesAbleBatchFrequency> extends Function<S, List<F>> { + } + + public FrequencyFunction<SpeciesBatch, SpeciesBatchFrequency> newSpeciesFrequenciesFunction() { + return new FrequencyFunction<SpeciesBatch, SpeciesBatchFrequency>() { + + @Override + public List<SpeciesBatchFrequency> apply(SpeciesBatch input) { + + return getAllSpeciesBatchFrequency(input.getId()); + } + }; + } + + public FrequencyFunction<BenthosBatch, BenthosBatchFrequency> newBenthosFrequenciesFunction() { + return new FrequencyFunction<BenthosBatch, BenthosBatchFrequency>() { + + @Override + public List<BenthosBatchFrequency> apply(BenthosBatch input) { + + return getAllBenthosBatchFrequency(input.getId()); + } + }; + } + + public <F extends SpeciesAbleBatchFrequency> Float countFrequenciesWeight(List<F> frequencies, boolean stopIfNullFound) { + Float result = null; + for (F frequency : frequencies) { + Float w = frequency.getWeight(); + if (w == null) { + + if (stopIfNullFound) { + break; + } + continue; + } + if (result == null) { + result = 0f; + } + result += w; + } + return result; + } + + public <F extends SpeciesAbleBatchFrequency> Integer countFrequenciesNumber(List<F> frequencies, boolean stopIfNullFound) { + Integer result = null; + for (F frequency : frequencies) { + Integer number = frequency.getNumber(); + if (number == null) { + + if (stopIfNullFound) { + break; + } + continue; + } + if (result == null) { + result = 0; + } + result += number; + } + return result; + } + //------------------------------------------------------------------------// //-- Technical methods --// //------------------------------------------------------------------------// @@ -272,6 +345,194 @@ return !(driver instanceof TuttiPersistenceNoDbImpl); } + public List<Caracteristic> getDefaultIndividualObservationCaracteristics() { + + TuttiProtocol protocol = getProtocol(); + + List<Caracteristic> result; + if (protocol != null) { + List<String> individualObservationPmfmId = getProtocol().getIndividualObservationPmfmId(); + if (CollectionUtils.isEmpty(individualObservationPmfmId)) { + + // no conf + result = Lists.newArrayList(); + + } else { + result = Lists.newArrayListWithCapacity(individualObservationPmfmId.size()); + for (String id : individualObservationPmfmId) { + Caracteristic caracteristic = getCaracteristic(Integer.valueOf(id)); + result.add(caracteristic); + } + } + + } else { + // no default caracteristics to use + result = Lists.newArrayList(); + } + + return result; + } + + public List<Caracteristic> getLengthStepCaracteristics(List<Caracteristic> caracteristics) { + + // get loaded protocol + TuttiProtocol protocol = getProtocol(); + + List<Caracteristic> result; + if (protocol != null) { + + result = Lists.newArrayListWithCapacity( + protocol.sizeLengthClassesPmfmId()); + + Map<String, Caracteristic> allCaractericsById = + TuttiEntities.splitById(caracteristics); + + if (!protocol.isLengthClassesPmfmIdEmpty()) { + for (String id : protocol.getLengthClassesPmfmId()) { + result.add(allCaractericsById.get(id)); + } + } + } else { + // no default caracteristics to use + result = Lists.newArrayList(); + } + + + result = Collections.unmodifiableList(result); + return result; + } + + public List<Species> getReferentSpeciesWithSurveyCode(List<Species> referentSpecies) { + + List<Species> result; + TuttiProtocol protocol = getProtocol(); + + if (protocol != null) { + // fill available species from protocol + result = Lists.newArrayList(); + if (!protocol.isSpeciesEmpty()) { + + // split by taxonId + Map<String, Species> map = TuttiEntities.splitByTaxonId(referentSpecies); + + for (SpeciesProtocol protocolSpecy : protocol.getSpecies()) { + String taxonId = String.valueOf(protocolSpecy.getSpeciesReferenceTaxonId()); + Species species = map.get(taxonId); + species.setSurveyCode(protocolSpecy.getSpeciesSurveyCode()); + result.add(species); + } + } + + } else { + + // no protocol, use default values + result = Lists.newArrayList(referentSpecies); + } + + result = Collections.unmodifiableList(result); + + return result; + } + + public List<Species> getReferentBenthosWithSurveyCode(List<Species> referentSpecies) { + List<Species> result; + + TuttiProtocol protocol = getProtocol(); + + if (protocol != null) { + + // fill available species from protocol + + result = Lists.newArrayList(); + if (!protocol.isBenthosEmpty()) { + + // split by taxonId + Map<String, Species> map = TuttiEntities.splitByTaxonId(referentSpecies); + + for (SpeciesProtocol protocolSpecy : protocol.getBenthos()) { + String taxonId = String.valueOf(protocolSpecy.getSpeciesReferenceTaxonId()); + Species species = map.get(taxonId); + species.setSurveyCode(protocolSpecy.getSpeciesSurveyCode()); + result.add(species); + } + } + + } else { + + // no protocol, use default values + result = Lists.newArrayList(referentSpecies); + } + + result = Collections.unmodifiableList(result); + + return result; + } + + public Map<Integer, SpeciesProtocol> toSpeciesProtocolMap() { + TuttiProtocol protocol = getProtocol(); + Preconditions.checkNotNull(protocol, + "Could not find protocol in ui context"); + + final Map<Integer, SpeciesProtocol> result = Maps.newHashMap(); + for (SpeciesProtocol sp : protocol.getSpecies()) { + result.put(sp.getSpeciesReferenceTaxonId(), sp); + } + return result; + } + + public Map<Integer, SpeciesProtocol> toBenthosProtocolMap() { + TuttiProtocol protocol = getProtocol(); + Preconditions.checkNotNull(protocol, + "Could not find protocol in ui context"); + + final Map<Integer, SpeciesProtocol> result = Maps.newHashMap(); + for (SpeciesProtocol sp : protocol.getBenthos()) { + result.put(sp.getSpeciesReferenceTaxonId(), sp); + } + return result; + } + + /** + * Return the speciesProtocol corresponding to the species of the given protocol. + * + * @param species the species to filter + * @return the speciesProtocol corresponding to the species of the given protocol. + * @since 2.6 + */ + public SpeciesProtocol getSpeciesProtocol(Species species) { + return getSpeciesProtocol(species, getProtocol().getSpecies()); + } + + /** + * Return the benthosProtocol corresponding to the species of the given protocol. + * + * @param species the species to filter + * @return the benthosProtocol corresponding to the species of the given protocol. + * @since 2.6 + */ + public SpeciesProtocol getBenthosProtocol(Species species) { + return getSpeciesProtocol(species, getProtocol().getBenthos()); + } + + /** + * Return all the speciesprotocol corresponding to the species of the batch + * + * @param species species to test + * @param speciesProtocols list of species protocol to filter + * @return all the speciesprotocol corresponding to the species of the batch + * @since 2.6 + */ + public SpeciesProtocol getSpeciesProtocol(Species species, + List<SpeciesProtocol> speciesProtocols) { + for (SpeciesProtocol speciesProtocol : speciesProtocols) { + if (species.getReferenceTaxonId().equals( + speciesProtocol.getSpeciesReferenceTaxonId())) { + return speciesProtocol; + } + } + return null; + } + @Override public void init() { @@ -346,16 +607,6 @@ } @Override - public List<Species> getAllSpecies(TuttiProtocol protocol) { - return driver.getAllSpecies(protocol); - } - - @Override - public List<Species> getAllReferentSpecies(TuttiProtocol protocol) { - return driver.getAllReferentSpecies(protocol); - } - - @Override public Species getSpeciesByReferenceTaxonIdWithVernacularCode(Integer referenceTaxonId) { return driver.getSpeciesByReferenceTaxonIdWithVernacularCode(referenceTaxonId); } @@ -485,16 +736,6 @@ return driver.getDeadOrAliveCaracteristic(); } -// @Override -// public Caracteristic getSampleIdCaracteristic() { -// return driver.getSampleIdCaracteristic(); -// } -// -// @Override -// public Caracteristic getOtolitheIdCaracteristic() { -// return driver.getOtolitheIdCaracteristic(); -// } - @Override public Caracteristic getPmfmIdCaracteristic() { return driver.getPmfmIdCaracteristic(); @@ -657,7 +898,18 @@ //-- Protocol methods --// //------------------------------------------------------------------------// + @Override + public TuttiProtocol getProtocol() { + return driver.getProtocol(); + } + + @Override + public void setProtocol(TuttiProtocol protocol) { + driver.setProtocol(protocol); + } + + @Override public boolean isProtocolExist(String id) { return driver.isProtocolExist(id); } Modified: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/TuttiDataContext.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/TuttiDataContext.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/TuttiDataContext.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,12 +26,10 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; -import fr.ifremer.tutti.persistence.entities.TuttiEntities; import fr.ifremer.tutti.persistence.entities.data.Cruise; import fr.ifremer.tutti.persistence.entities.data.FishingOperation; import fr.ifremer.tutti.persistence.entities.data.Program; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; -import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; @@ -40,7 +38,6 @@ import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.persistence.entities.referential.Vessel; import fr.ifremer.tutti.service.config.TuttiServiceConfig; -import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -50,10 +47,8 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.Closeable; -import java.util.Collections; import java.util.Date; import java.util.List; -import java.util.Map; /** * Data context of ui. @@ -123,7 +118,7 @@ protected Cruise cruise; - protected TuttiProtocol protocol; +// protected TuttiProtocol protocol; protected FishingOperation fishingOperation; @@ -191,13 +186,16 @@ public void open(TuttiServiceConfig config, PersistenceService persistenceService) { close(); this.service = persistenceService; + + // attach protocol to service + this.service.setProtocol(getProtocol()); loadSampleCategoryModel(config.getPersistenceConfig().getSampleCategoryModel()); } @Override public void close() { + clearContext(); service = null; - clearContext(); } public void clearContext() { @@ -436,14 +434,14 @@ public TuttiProtocol getProtocol() { checkOpened(); - if (protocol == null) { - if (isProtocolFilled()) { - String id = getProtocolId(); - if (log.isInfoEnabled()) { - log.info("Loading protocol: " + id); - } - protocol = service.getProtocol(id); + TuttiProtocol protocol = service.getProtocol(); + if (protocol == null && isProtocolFilled()) { + String id = getProtocolId(); + if (log.isInfoEnabled()) { + log.info("Loading protocol: " + id); } + protocol = service.getProtocol(id); + service.setProtocol(protocol); } return protocol; } @@ -488,27 +486,32 @@ checkOpened(); if (lengthStepCaracteristics == null) { - if (isProtocolFilled()) { - - // get loaded protocol - protocol = getProtocol(); - lengthStepCaracteristics = Lists.newArrayListWithCapacity( - protocol.sizeLengthClassesPmfmId()); - - Map<String, Caracteristic> allCaractericsById = - TuttiEntities.splitById(getCaracteristics()); - - if (!protocol.isLengthClassesPmfmIdEmpty()) { - for (String id : protocol.getLengthClassesPmfmId()) { - lengthStepCaracteristics.add(allCaractericsById.get(id)); - } - } - } else { - lengthStepCaracteristics = Lists.newArrayList( - getCaracteristics()); + if (log.isInfoEnabled()) { + log.info("Loading lengthStepCaracteristics"); } + lengthStepCaracteristics = service.getLengthStepCaracteristics(getCaracteristics()); - lengthStepCaracteristics = Collections.unmodifiableList(lengthStepCaracteristics); +// if (isProtocolFilled()) { +// +// // get loaded protocol +// protocol = getProtocol(); +// lengthStepCaracteristics = Lists.newArrayListWithCapacity( +// protocol.sizeLengthClassesPmfmId()); +// +// Map<String, Caracteristic> allCaractericsById = +// TuttiEntities.splitById(getCaracteristics()); +// +// if (!protocol.isLengthClassesPmfmIdEmpty()) { +// for (String id : protocol.getLengthClassesPmfmId()) { +// lengthStepCaracteristics.add(allCaractericsById.get(id)); +// } +// } +// } else { +// lengthStepCaracteristics = Lists.newArrayList( +// getCaracteristics()); +// } +// +// lengthStepCaracteristics = Collections.unmodifiableList(lengthStepCaracteristics); } return lengthStepCaracteristics; } @@ -539,36 +542,42 @@ checkOpened(); if (referentSpeciesWithSurveyCode == null) { - if (isProtocolFilled()) { + if (log.isInfoEnabled()) { + log.info("Loading referentSpecies"); + } - // get loaded protocol + referentSpeciesWithSurveyCode = service.getReferentSpeciesWithSurveyCode(getReferentSpecies()); - TuttiProtocol protocol = getProtocol(); - Preconditions.checkNotNull(protocol, - "Could not find protocol in ui context"); - - // fill available species from protocol - referentSpeciesWithSurveyCode = Lists.newArrayList(); - if (!protocol.isSpeciesEmpty()) { - - // split by taxonId - Map<String, Species> map = TuttiEntities.splitByTaxonId(getReferentSpecies()); - - for (SpeciesProtocol protocolSpecy : protocol.getSpecies()) { - String taxonId = String.valueOf(protocolSpecy.getSpeciesReferenceTaxonId()); - Species species = map.get(taxonId); - species.setSurveyCode(protocolSpecy.getSpeciesSurveyCode()); - referentSpeciesWithSurveyCode.add(species); - } - } - - } else { - - // no protocol, use default values - referentSpeciesWithSurveyCode = Lists.newArrayList(getReferentSpecies()); - } - - referentSpeciesWithSurveyCode = Collections.unmodifiableList(referentSpeciesWithSurveyCode); +// if (isProtocolFilled()) { +// +// // get loaded protocol +// +// TuttiProtocol protocol = getProtocol(); +// Preconditions.checkNotNull(protocol, +// "Could not find protocol in ui context"); +// +// // fill available species from protocol +// referentSpeciesWithSurveyCode = Lists.newArrayList(); +// if (!protocol.isSpeciesEmpty()) { +// +// // split by taxonId +// Map<String, Species> map = TuttiEntities.splitByTaxonId(getReferentSpecies()); +// +// for (SpeciesProtocol protocolSpecy : protocol.getSpecies()) { +// String taxonId = String.valueOf(protocolSpecy.getSpeciesReferenceTaxonId()); +// Species species = map.get(taxonId); +// species.setSurveyCode(protocolSpecy.getSpeciesSurveyCode()); +// referentSpeciesWithSurveyCode.add(species); +// } +// } +// +// } else { +// +// // no protocol, use default values +// referentSpeciesWithSurveyCode = Lists.newArrayList(getReferentSpecies()); +// } +// +// referentSpeciesWithSurveyCode = Collections.unmodifiableList(referentSpeciesWithSurveyCode); } return referentSpeciesWithSurveyCode; } @@ -577,37 +586,43 @@ checkOpened(); if (referentBenthosWithSurveyCode == null) { - if (isProtocolFilled()) { + if (log.isInfoEnabled()) { + log.info("Loading referentBenthos"); + } - // get loaded protocol + referentBenthosWithSurveyCode = service.getReferentBenthosWithSurveyCode(getReferentSpecies()); - TuttiProtocol protocol = getProtocol(); - Preconditions.checkNotNull(protocol, - "Could not find protocol in ui context"); - - // fill available species from protocol - - referentBenthosWithSurveyCode = Lists.newArrayList(); - if (!protocol.isBenthosEmpty()) { - - // split by taxonId - Map<String, Species> map = TuttiEntities.splitByTaxonId(getReferentSpecies()); - - for (SpeciesProtocol protocolSpecy : protocol.getBenthos()) { - String taxonId = String.valueOf(protocolSpecy.getSpeciesReferenceTaxonId()); - Species species = map.get(taxonId); - species.setSurveyCode(protocolSpecy.getSpeciesSurveyCode()); - referentBenthosWithSurveyCode.add(species); - } - } - - } else { - - // no protocol, use default values - referentBenthosWithSurveyCode = Lists.newArrayList(getReferentSpecies()); - } - - referentBenthosWithSurveyCode = Collections.unmodifiableList(referentBenthosWithSurveyCode); +// if (isProtocolFilled()) { +// +// // get loaded protocol +// +// TuttiProtocol protocol = getProtocol(); +// Preconditions.checkNotNull(protocol, +// "Could not find protocol in ui context"); +// +// // fill available species from protocol +// +// referentBenthosWithSurveyCode = Lists.newArrayList(); +// if (!protocol.isBenthosEmpty()) { +// +// // split by taxonId +// Map<String, Species> map = TuttiEntities.splitByTaxonId(getReferentSpecies()); +// +// for (SpeciesProtocol protocolSpecy : protocol.getBenthos()) { +// String taxonId = String.valueOf(protocolSpecy.getSpeciesReferenceTaxonId()); +// Species species = map.get(taxonId); +// species.setSurveyCode(protocolSpecy.getSpeciesSurveyCode()); +// referentBenthosWithSurveyCode.add(species); +// } +// } +// +// } else { +// +// // no protocol, use default values +// referentBenthosWithSurveyCode = Lists.newArrayList(getReferentSpecies()); +// } +// +// referentBenthosWithSurveyCode = Collections.unmodifiableList(referentBenthosWithSurveyCode); } return referentBenthosWithSurveyCode; } @@ -617,7 +632,8 @@ if (log.isInfoEnabled()) { log.info("Loading allSpecies"); } - species = service.getAllSpecies(protocol); +// species = service.getAllSpecies(protocol); + species = service.getAllSpecies(); } return species; } @@ -627,7 +643,7 @@ if (log.isInfoEnabled()) { log.info("Loading allReferentSpecies"); } - referentSpecies = service.getAllReferentSpecies(protocol); + referentSpecies = service.getAllReferentSpecies(); } return referentSpecies; } @@ -693,29 +709,31 @@ if (log.isInfoEnabled()) { log.info("Loading defaultIndividualObservationCaracteristics"); } - List<Caracteristic> list; - if (isProtocolFilled()) { - List<String> individualObservationPmfmId = getProtocol().getIndividualObservationPmfmId(); - if (CollectionUtils.isEmpty(individualObservationPmfmId)) { + defaultIndividualObservationCaracteristics = service.getDefaultIndividualObservationCaracteristics(); - // no conf - list = Lists.newArrayList(); - - } else { - list = Lists.newArrayListWithCapacity(individualObservationPmfmId.size()); - for (String id : individualObservationPmfmId) { - Caracteristic caracteristic = service.getCaracteristic(Integer.valueOf(id)); - list.add(caracteristic); - } - } - - } else { - // no default caracteristics to use - list = Lists.newArrayList(); - } - - defaultIndividualObservationCaracteristics = - Collections.unmodifiableList(list); +// List<Caracteristic> list; +// if (isProtocolFilled()) { +// List<String> individualObservationPmfmId = getProtocol().getIndividualObservationPmfmId(); +// if (CollectionUtils.isEmpty(individualObservationPmfmId)) { +// +// // no conf +// list = Lists.newArrayList(); +// +// } else { +// list = Lists.newArrayListWithCapacity(individualObservationPmfmId.size()); +// for (String id : individualObservationPmfmId) { +// Caracteristic caracteristic = service.getCaracteristic(Integer.valueOf(id)); +// list.add(caracteristic); +// } +// } +// +// } else { +// // no default caracteristics to use +// list = Lists.newArrayList(); +// } +// +// defaultIndividualObservationCaracteristics = +// Collections.unmodifiableList(list); } return defaultIndividualObservationCaracteristics; } @@ -725,7 +743,10 @@ } public void resetProtocol() { - protocol = null; + if (service != null) { + service.setProtocol(null); + } +// protocol = null; lengthStepCaracteristics = null; defaultIndividualObservationCaracteristics = null; } Modified: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/TuttiServiceContext.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/TuttiServiceContext.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/TuttiServiceContext.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -90,8 +90,8 @@ Constructor<? extends TuttiService> constructor = key.getConstructor(); Preconditions.checkNotNull(constructor); TuttiService service = constructor.newInstance(); - if (log.isInfoEnabled()) { - log.info("New service " + service); + if (log.isDebugEnabled()) { + log.debug("New service " + service); } service.setServiceContext(TuttiServiceContext.this); return service; @@ -130,8 +130,8 @@ public <S extends TuttiService> S reloadService(Class<S> serviceType) { S service = (S) services.getIfPresent(serviceType); if (service != null) { - if (log.isInfoEnabled()) { - log.info("Close service " + service); + if (log.isDebugEnabled()) { + log.debug("Close service " + service); } IOUtils.closeQuietly(service); } @@ -144,8 +144,8 @@ public void close() throws IOException { for (TuttiService service : services.asMap().values()) { - if (log.isInfoEnabled()) { - log.info("Close service " + service); + if (log.isDebugEnabled()) { + log.debug("Close service " + service); } IOUtils.closeQuietly(service); } Copied: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/WeightUnit.java (from rev 1246, trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/WeightUnit.java) =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/WeightUnit.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/WeightUnit.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,94 @@ +package fr.ifremer.tutti.service; + +import static org.nuiton.i18n.I18n._; +import static org.nuiton.i18n.I18n.n_; + +/** + * Different types of weight unit. + * <p/> + * Created on 09/22/13. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 2.5 + */ +public enum WeightUnit { + + G(n_("tutti.common.unit.g"), n_("tutti.common.unit.short.g"), 1, "\\d{0,6}(\\.\\d{0,1})?") { + @Override + public Float fromEntity(Float weight) { + return weight == null ? null : weight * 1000; + } + + @Override + public Float toEntity(Float weight) { + return weight == null ? null : weight / 1000.0f; + } + }, + KG(n_("tutti.common.unit.kg"), n_("tutti.common.unit.short.kg"), 4, "\\d{0,6}(\\.\\d{0,4})?") { + @Override + public Float fromEntity(Float weight) { + return weight; + } + + @Override + public Float toEntity(Float weight) { + return weight; + } + }; + + private final String i18nShortKey; + + private final String i18nKey; + + private final int numberDigits; + + private final String numberEditorPattern; + + WeightUnit(String i18nKey, String i18nShortKey, int numberDigits, String numberEditorPattern) { + this.i18nKey = i18nKey; + this.i18nShortKey = i18nShortKey; + this.numberDigits = numberDigits; + this.numberEditorPattern = numberEditorPattern; + } + + public String getLabel() { + return _(i18nKey); + } + + public String getShortLabel() { + return _(i18nShortKey); + } + + public int getNumberDigits() { + return numberDigits; + } + + public String getNumberEditorPattern() { + return numberEditorPattern; + } + + /** + * Transform the given {@code weight} coming from db to ui. + * + * @param weight weigth to transform + * @return the ui representation of the given {@code weight}. + */ + public abstract Float fromEntity(Float weight); + + /** + * Transform the given {@code weight} coming from ui to db. + * + * @param weight weigth to transform + * @return the db representation of the given {@code weight}. + */ + public abstract Float toEntity(Float weight); + + public String decorateLabel(String label) { + return String.format("%s (%s)", label, getShortLabel()); + } + + public String decorateTip(String tip) { + String unit = _("tutti.common.unit"); + return String.format("%s (%s %s)", tip, unit, getLabel()); + } +} Modified: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/ExportCatchesReportService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/ExportCatchesReportService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/ExportCatchesReportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -72,7 +72,7 @@ protected PersistenceService persistenceService; - protected TuttiWeightComputingService tuttiWeightComputingService; + protected WeightComputingService weightComputingService; public ExportCatchesReportService() { super(); @@ -95,7 +95,7 @@ public void setServiceContext(TuttiServiceContext context) { super.setServiceContext(context); persistenceService = getService(PersistenceService.class); - tuttiWeightComputingService = getService(TuttiWeightComputingService.class); + weightComputingService = getService(WeightComputingService.class); } /** @@ -137,12 +137,12 @@ CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(fishingOperationId); BatchContainer<SpeciesBatch> rootSpeciesBatch = - tuttiWeightComputingService.getComputedSpeciesBatches(fishingOperation); + weightComputingService.getComputedSpeciesBatches(fishingOperation); BatchContainer<BenthosBatch> rootBenthosBatch = - tuttiWeightComputingService.getComputedBenthosBatches(fishingOperation); + weightComputingService.getComputedBenthosBatches(fishingOperation); - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, rootSpeciesBatch, rootBenthosBatch, null); + weightComputingService.computeCatchBatchWeights(catchBatch, rootSpeciesBatch, rootBenthosBatch, null); // create operation data model Map<String, Object> op = createOperation(fishingOperation); Deleted: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,765 +0,0 @@ -package fr.ifremer.tutti.service.catches; - -/* - * #%L - * Tutti :: Service - * $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.TuttiBusinessException; -import fr.ifremer.tutti.persistence.entities.TuttiEntities; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatchFrequency; -import fr.ifremer.tutti.persistence.entities.data.CatchBatch; -import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; -import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; -import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; -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.service.AbstractTuttiService; -import fr.ifremer.tutti.service.DecoratorService; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.TuttiServiceContext; -import fr.ifremer.tutti.service.ValidationService; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorResult; - -import java.util.List; -import java.util.Map; - -import static org.nuiton.i18n.I18n._; - -/** - * @author kmorin <kmorin@codelutin.com> - * @since 1.3 - */ -public class TuttiWeightComputingService extends AbstractTuttiService { - - private static final Log log = - LogFactory.getLog(TuttiWeightComputingService.class); - - protected PersistenceService persistenceService; - - protected ValidationService validationService; - - protected DecoratorService decoratorService; - - protected SampleCategoryModel sampleCategoryModel; - - @Override - public void setServiceContext(TuttiServiceContext context) { - super.setServiceContext(context); - persistenceService = getService(PersistenceService.class); - validationService = getService(ValidationService.class); - decoratorService = getService(DecoratorService.class); - sampleCategoryModel = context.getSampleCategoryModel(); - } - - /** - * To check if can compute for any fishing operation of the cruise given - * by his id. - * <p/> - * If no error found, then return is a empty map, otherwise the first error - * found for any bad fishing operation. - * <p/> - * Result keys are fishing operation id, values the first error for - * the fishing operation. - * - * @param cruiseId id of the cruise to check. - * @return map of errors, or empty map if no error found. - * @since 1.4 - */ - public Map<String, String> checkCruise(String cruiseId) { - - if (log.isDebugEnabled()) { - log.debug("Will check cruise: " + cruiseId); - } - Map<String, String> result = Maps.newTreeMap(); - - List<FishingOperation> allFishingOperation = - persistenceService.getAllFishingOperation(cruiseId); - - for (FishingOperation fishingOperation : allFishingOperation) { - - String fishingOperationId = fishingOperation.getId(); - - boolean withCatchBatch = - persistenceService.isFishingOperationWithCatchBatch( - fishingOperationId); - - if (!withCatchBatch) { - if (log.isWarnEnabled()) { - log.warn("Skip fishing operation " + fishingOperation + - " since no catchBatch associated."); - } - continue; - } - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(fishingOperationId); - - BatchContainer<SpeciesBatch> rootSpeciesBatch; - try { - rootSpeciesBatch = getComputedSpeciesBatches(fishingOperation); - - } catch (TuttiBusinessException e) { - result.put(fishingOperationId, e.getMessage()); - rootSpeciesBatch = persistenceService.getRootSpeciesBatch(fishingOperationId, null); - } - - BatchContainer<BenthosBatch> rootBenthosBatch; - try { - rootBenthosBatch = getComputedBenthosBatches(fishingOperation); - - } catch (TuttiBusinessException e) { - result.put(fishingOperationId, e.getMessage()); - rootBenthosBatch = persistenceService.getRootBenthosBatch(fishingOperationId, null); - } - - BatchContainer<MarineLitterBatch> rootMarineLitterBatch; - try { - Float weight = catchBatch == null ? null : catchBatch.getMarineLitterTotalWeight(); - rootMarineLitterBatch = getComputedMarineLitterBatches(fishingOperation, weight); - - } catch (TuttiBusinessException e) { - result.put(fishingOperationId, e.getMessage()); - rootMarineLitterBatch = persistenceService.getRootMarineLitterBatch(fishingOperationId); - } - - try { - if (catchBatch != null) { - computeCatchBatchWeights(catchBatch, - rootSpeciesBatch, - rootBenthosBatch, - rootMarineLitterBatch); - } - } catch (TuttiBusinessException e) { - result.put(fishingOperationId, e.getMessage()); - } - } - return result; - } - - /** - * Compute the weights of the catch batch (not the ones of the species, benthos nor marine litter batches) - * - * @param catchBatch the catch batch with the weights to compute - * @param rootSpeciesBatch the species batches with already computed weights - * @param rootBenthosBatch the benthos batches with already computed weights - * @param rootMarineLitterBatch the marine litter batches with already computed weights - */ - public void computeCatchBatchWeights(CatchBatch catchBatch, - BatchContainer<SpeciesBatch> rootSpeciesBatch, - BatchContainer<BenthosBatch> rootBenthosBatch, - BatchContainer<MarineLitterBatch> rootMarineLitterBatch) { - - // Species - Float speciesTotalComputedSortedWeight = 0f; - Float speciesTotalComputedUnsortedWeight = 0f; - - if (rootSpeciesBatch != null) { - for (int i = 0; i < rootSpeciesBatch.getChildren().size(); i++) { - SpeciesBatch row = rootSpeciesBatch.getChildren().get(i); -// Float weight = row.getSampleCategoryWeight(); -// if (weight == null) { -// weight = row.getSampleCategoryComputedWeight(); -// } - Float weight = TuttiEntities.getValueOrComputedValue( - row.getSampleCategoryWeight(), - row.getSampleCategoryComputedWeight()); - if (weight == null) { - break; - } - - if (persistenceService.isVracSpeciesBatch(row)) { - speciesTotalComputedSortedWeight += weight; - } else { - speciesTotalComputedUnsortedWeight += weight; - } - } - } - - Number inertWeight = catchBatch.getSpeciesTotalInertWeight(); - if (inertWeight != null) { - speciesTotalComputedSortedWeight += inertWeight.floatValue(); - } else { - catchBatch.setSpeciesTotalInertComputedWeight(0f); - } - - Number livingNotItemizedWeight = catchBatch.getSpeciesTotalLivingNotItemizedWeight(); - if (livingNotItemizedWeight != null) { - speciesTotalComputedSortedWeight += livingNotItemizedWeight.floatValue(); - } else { - catchBatch.setSpeciesTotalLivingNotItemizedComputedWeight(0f); - } - - catchBatch.setSpeciesTotalSampleSortedComputedWeight(speciesTotalComputedSortedWeight); - - Float speciesTotalSortedWeight = catchBatch.getSpeciesTotalSortedWeight(); - if (speciesTotalSortedWeight == null) { - speciesTotalSortedWeight = speciesTotalComputedSortedWeight; - catchBatch.setSpeciesTotalSortedComputedWeight(speciesTotalSortedWeight); - - } else if (speciesTotalSortedWeight < speciesTotalComputedSortedWeight) { - throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.species.incoherentTotalSorted")); - } - catchBatch.setSpeciesTotalUnsortedComputedWeight(speciesTotalComputedUnsortedWeight); - - if (speciesTotalSortedWeight == null) { - speciesTotalSortedWeight = catchBatch.getSpeciesTotalSortedComputedWeight(); - } - Float speciesTotalWeight = speciesTotalComputedUnsortedWeight + speciesTotalSortedWeight; - catchBatch.setSpeciesTotalComputedWeight(speciesTotalWeight); - - // Benthos - Float benthosTotalComputedSortedWeight = 0f; - Float benthosTotalComputedUnsortedWeight = 0f; - - if (rootBenthosBatch != null) { - for (int i = 0; i < rootBenthosBatch.getChildren().size(); i++) { - BenthosBatch row = rootBenthosBatch.getChildren().get(i); - Float weight = TuttiEntities.getValueOrComputedValue( - row.getSampleCategoryWeight(), - row.getSampleCategoryComputedWeight()); -// Float weight = row.getSampleCategoryWeight(); -// if (weight == null) { -// weight = row.getSampleCategoryComputedWeight(); -// } - if (weight == null) { - break; - } - - if (persistenceService.isVracBenthosBatch(row)) { - benthosTotalComputedSortedWeight += weight; - } else { - benthosTotalComputedUnsortedWeight += weight; - } - } - } - - inertWeight = catchBatch.getBenthosTotalInertWeight(); - if (inertWeight != null) { - benthosTotalComputedSortedWeight += inertWeight.floatValue(); - } else { - catchBatch.setBenthosTotalInertComputedWeight(0f); - } - - livingNotItemizedWeight = catchBatch.getBenthosTotalLivingNotItemizedWeight(); - if (livingNotItemizedWeight != null) { - benthosTotalComputedSortedWeight += livingNotItemizedWeight.floatValue(); - } else { - catchBatch.setBenthosTotalLivingNotItemizedComputedWeight(0f); - } - - catchBatch.setBenthosTotalSampleSortedComputedWeight(benthosTotalComputedSortedWeight); - - Float benthosTotalSortedWeight = catchBatch.getBenthosTotalSortedWeight(); - if (benthosTotalSortedWeight == null) { - benthosTotalSortedWeight = benthosTotalComputedSortedWeight; - catchBatch.setBenthosTotalSortedComputedWeight(benthosTotalSortedWeight); - - } else if (benthosTotalSortedWeight < benthosTotalComputedSortedWeight) { - throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.benthos.incoherentTotalSorted")); - } - catchBatch.setBenthosTotalUnsortedComputedWeight(benthosTotalComputedUnsortedWeight); - - if (benthosTotalSortedWeight == null) { - benthosTotalSortedWeight = catchBatch.getBenthosTotalSortedComputedWeight(); - } - Float benthosTotalWeight = benthosTotalComputedUnsortedWeight + benthosTotalSortedWeight; - catchBatch.setBenthosTotalComputedWeight(benthosTotalWeight); - - // Marine litter - Float marineLitterTotalComputedWeight = 0f; - - if (rootMarineLitterBatch != null) { - for (int i = 0; i < rootMarineLitterBatch.getChildren().size(); i++) { - MarineLitterBatch row = rootMarineLitterBatch.getChildren().get(i); - Float rowWeight = row.getWeight(); - if (rowWeight == null) { - marineLitterTotalComputedWeight = null; - break; - } - marineLitterTotalComputedWeight += rowWeight; - } - } - catchBatch.setMarineLitterTotalComputedWeight(marineLitterTotalComputedWeight); - - Float marineLitterTotalWeight = catchBatch.getMarineLitterTotalWeight(); - if (marineLitterTotalWeight == null) { - marineLitterTotalWeight = marineLitterTotalComputedWeight; - - } else if (marineLitterTotalComputedWeight != null && marineLitterTotalWeight < marineLitterTotalComputedWeight) { - throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.marineLitter.incoherentTotal")); - } - // nothing to do with the marine litter weight, it is an isolated weight - - // Catch - Float totalUnsortedWeight = catchBatch.getSpeciesTotalUnsortedComputedWeight() + - catchBatch.getBenthosTotalUnsortedComputedWeight(); - - Float totalSortedWeight = speciesTotalSortedWeight + benthosTotalSortedWeight; - - catchBatch.setCatchTotalSortedComputedWeight(totalSortedWeight); - catchBatch.setCatchTotalUnsortedComputedWeight(totalUnsortedWeight); - - Float totalWeight = catchBatch.getCatchTotalWeight(); - Float rejectedWeight = catchBatch.getCatchTotalRejectedWeight(); - - if (rejectedWeight == null && totalWeight != null) { - if (!totalWeight.equals(totalUnsortedWeight - + totalSortedWeight)) { - throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.incoherentTotal")); - - } else { - catchBatch.setCatchTotalRejectedComputedWeight(totalWeight - - totalUnsortedWeight - - totalSortedWeight); - } - - } else if (totalWeight == null) { - if (rejectedWeight == null) { - rejectedWeight = 0f; - catchBatch.setCatchTotalRejectedComputedWeight(0f); - } - catchBatch.setCatchTotalComputedWeight(totalUnsortedWeight - + totalSortedWeight - + rejectedWeight); - - } else if (!totalWeight.equals(totalUnsortedWeight + totalSortedWeight + rejectedWeight)) { - throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.incoherentTotal")); - } - } - - private int currentSpeciesRowIndex; - - public BatchContainer<SpeciesBatch> getComputedSpeciesBatches(FishingOperation operation) { - - BatchContainer<SpeciesBatch> rootSpeciesBatch = null; - - if (persistenceService.isFishingOperationWithCatchBatch(operation.getId())) { - rootSpeciesBatch = persistenceService.getRootSpeciesBatch(operation.getId(), null); - - currentSpeciesRowIndex = 0; - if (rootSpeciesBatch != null) { - List<SpeciesBatch> roots = rootSpeciesBatch.getChildren(); - - for (SpeciesBatch batch : roots) { - computeSpeciesBatch(batch); - } - } - } - - return rootSpeciesBatch; - } - - protected String getCategoryLabel(Integer sampleCategoryId) { - SampleCategoryModelEntry category = - sampleCategoryModel.getCategoryById(sampleCategoryId); - String result = category.getLabel(); - return result; - } - - public Float computeSpeciesBatch(SpeciesBatch batch) { - Float result = null; - int thisIndex = currentSpeciesRowIndex++; - Float categoryWeight = batch.getSampleCategoryWeight(); - Float rowWeight = batch.getWeight(); - String species = decoratorService.getDecoratorByType(Species.class).toString(batch.getSpecies()); - String categoryValue = decoratorService.getDecorator(batch.getSampleCategoryValue()) - .toString(batch.getSampleCategoryValue()); - - NuitonValidatorResult validation = validationService.validateSpeciesBatch(batch); - if (!validation.isValid()) { - List<String> messages = validation.getErrorMessages(SpeciesBatch.PROPERTY_WEIGHT); - String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); - throw new TuttiWeightComputingException(_(messages.get(0), - species, - categoryLabel, - categoryValue, - batch.getWeight(), - batch.getSampleCategoryWeight()), - SpeciesBatch.PROPERTY_WEIGHT, - thisIndex); - } - - List<SpeciesBatch> children = batch.getChildBatchs(); - // if the row is not a leaf - if (batch.sizeChildBatchs() > 0) { - Float sum = 0f; - // make the sum of the children weights - for (SpeciesBatch child : children) { - Float weight = computeSpeciesBatch(child); - if (weight == null) { - sum = null; - break; - } - sum += weight; - } - - if (sum != null) { - if (categoryWeight == null) { - batch.setSampleCategoryComputedWeight(sum); - - } else if (categoryWeight < sum) { - String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); - throw new TuttiWeightComputingException( - _("tutti.service.operations.computeWeights.error.species.incoherentParentCategoryWeight", - species, - categoryLabel, - categoryValue, - categoryWeight, - sum), - SpeciesBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, - thisIndex); - - } else { - sum = categoryWeight; - } - result = sum; - } - - } else {// the row is a leaf - - batch.setComputedWeight(null); - - List<SpeciesBatchFrequency> frequencies = persistenceService.getAllSpeciesBatchFrequency(batch.getId()); - - if (CollectionUtils.isNotEmpty(frequencies)) { - // if there are frequencies, then compute their weight - Float frequencyWeight = 0f; - for (SpeciesBatchFrequency frequency : frequencies) { - Float w = frequency.getWeight(); - if (w == null) { - - // can't sum when a null value appears - frequencyWeight = null; - break; - - } else if (frequencyWeight != null) { - - // still can sum weights - frequencyWeight += w; - } - } - - if (categoryWeight == null && rowWeight != null) { -// throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.incoherentRowWeightCategory")); - - } else if (rowWeight != null && frequencyWeight != null - && !rowWeight.equals(frequencyWeight)) { - - String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); - - throw new TuttiWeightComputingException( - _("tutti.service.operations.computeWeights.error.species.incoherentRowWeightFrequency", - species, - categoryLabel, - categoryValue, - frequencyWeight, - rowWeight), - SpeciesBatch.PROPERTY_WEIGHT, - thisIndex); - - } else if (categoryWeight == null && frequencyWeight != null) { - // if the category weight is null and the frequencies have a weight, - // then this weight is the result - batch.setSampleCategoryComputedWeight(frequencyWeight); - result = frequencyWeight; - - } else if (frequencyWeight != null - && !frequencyWeight.equals(categoryWeight)) { - - // if the weight of the frequencies is different from the category - // weight, then set the weight of the sample - if (frequencyWeight > categoryWeight) { - - String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); - - throw new TuttiWeightComputingException( - _("tutti.service.operations.computeWeights.error.species.incoherentCategoryWeight", - species, - categoryLabel, - categoryValue, - frequencyWeight, - categoryWeight), - SpeciesBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, - thisIndex); - - } else if (rowWeight == null) { - batch.setComputedWeight(frequencyWeight); - - } - result = categoryWeight; - - } else { - result = categoryWeight; - } - - // compute number from frequencies - Integer frequencyNumber = 0; - for (SpeciesBatchFrequency frequency : frequencies) { - Integer c = frequency.getNumber(); - frequencyNumber += c; - } - batch.setComputedNumber(frequencyNumber); - - } else { - result = categoryWeight; - } - } - if (result == null) { - - String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); - - throw new TuttiWeightComputingException( - _("tutti.service.operations.computeWeights.error.species.noWeight", - species, - categoryLabel, - categoryValue), - SpeciesBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, - thisIndex); - } - - return result; - } - - private int currentBenthosRowIndex; - - public BatchContainer<BenthosBatch> getComputedBenthosBatches(FishingOperation operation) { - - BatchContainer<BenthosBatch> rootBenthosBatch = null; - - if (persistenceService.isFishingOperationWithCatchBatch(operation.getId())) { - rootBenthosBatch = persistenceService.getRootBenthosBatch(operation.getId(), null); - - currentBenthosRowIndex = 0; - if (rootBenthosBatch != null) { - List<BenthosBatch> roots = rootBenthosBatch.getChildren(); - - for (BenthosBatch batch : roots) { - computeBenthosBatch(batch); - } - } - } - - return rootBenthosBatch; - } - - public Float computeBenthosBatch(BenthosBatch batch) { - Float result = null; - int thisIndex = currentBenthosRowIndex++; - Float categoryWeight = batch.getSampleCategoryWeight(); - Float rowWeight = batch.getWeight(); - String species = decoratorService.getDecoratorByType(Species.class).toString(batch.getSpecies()); - String categoryValue = decoratorService.getDecorator(batch.getSampleCategoryValue()) - .toString(batch.getSampleCategoryValue()); - - NuitonValidatorResult validation = validationService.validateBenthosBatch(batch); - if (!validation.isValid()) { - List<String> messages = validation.getErrorMessages(BenthosBatch.PROPERTY_WEIGHT); - - String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); - throw new TuttiWeightComputingException(_(messages.get(0), - species, - categoryLabel, - categoryValue, - batch.getWeight(), - batch.getSampleCategoryWeight()), - BenthosBatch.PROPERTY_WEIGHT, - thisIndex); - } - - List<BenthosBatch> children = batch.getChildBatchs(); - // if the row is not a leaf - if (!batch.isChildBatchsEmpty()) { - Float sum = 0f; - // make the sum of the children weights - for (BenthosBatch child : children) { - Float weight = computeBenthosBatch(child); - if (weight == null) { - sum = null; - break; - } - sum += weight; - } - - if (sum != null) { - if (categoryWeight == null) { - batch.setSampleCategoryComputedWeight(sum); - - } else if (categoryWeight < sum) { - String categoryLabel = - getCategoryLabel(batch.getSampleCategoryId()); - - throw new TuttiWeightComputingException( - _("tutti.service.operations.computeWeights.error.benthos.incoherentParentCategoryWeight", - species, - categoryLabel, - categoryValue, - categoryWeight, - sum), - BenthosBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, - thisIndex); - - } else { - sum = categoryWeight; - } - result = sum; - - } - - } else {// the row is a leaf - - batch.setComputedWeight(null); - - List<BenthosBatchFrequency> frequencies = persistenceService.getAllBenthosBatchFrequency(batch.getId()); - - if (CollectionUtils.isNotEmpty(frequencies)) { - // if there are frequencies, then compute their weight - Float frequencyWeight = 0f; - for (BenthosBatchFrequency frequency : frequencies) { - Float w = frequency.getWeight(); - if (w == null) { - - // can't sum when a null value appears - frequencyWeight = null; - break; - - } else if (frequencyWeight != null) { - - // still can sum weights - frequencyWeight += w; - } - } - - if (categoryWeight == null && rowWeight != null) { -// throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.incoherentRowWeightCategory")); - - } else if (rowWeight != null && frequencyWeight != null - && !rowWeight.equals(frequencyWeight)) { - - String categoryLabel = - getCategoryLabel(batch.getSampleCategoryId()); - - throw new TuttiWeightComputingException( - _("tutti.service.operations.computeWeights.error.benthos.incoherentRowWeightFrequency", - species, - categoryLabel, - categoryValue, - rowWeight, - categoryWeight), - BenthosBatch.PROPERTY_WEIGHT, - thisIndex); - - } else if (categoryWeight == null && frequencyWeight != null) { - // if the category weight is null and the frequencies have a weight, - // then this weight is the result - batch.setSampleCategoryComputedWeight(frequencyWeight); - result = frequencyWeight; - - } else if (frequencyWeight != null - && !frequencyWeight.equals(categoryWeight)) { - - // if the weight of the frequencies is different from the category - // weight, then set the weight of the sample - if (frequencyWeight > categoryWeight) { - - String categoryLabel = - getCategoryLabel(batch.getSampleCategoryId()); - - throw new TuttiWeightComputingException( - _("tutti.service.operations.computeWeights.error.benthos.incoherentCategoryWeight", - species, - categoryLabel, - categoryValue, - frequencyWeight, - categoryWeight), - BenthosBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, - thisIndex); - - } else if (rowWeight == null) { - batch.setComputedWeight(frequencyWeight); - - } - result = categoryWeight; - - } else { - result = categoryWeight; - } - - // compute number from frequencies - Integer frequencyNumber = 0; - for (BenthosBatchFrequency frequency : frequencies) { - Integer c = frequency.getNumber(); - frequencyNumber += c; - } - batch.setComputedNumber(frequencyNumber); - } else { - result = categoryWeight; - } - } - if (result == null) { - - String categoryLabel = - getCategoryLabel(batch.getSampleCategoryId()); - - throw new TuttiWeightComputingException( - _("tutti.service.operations.computeWeights.error.benthos.noWeight", - species, - categoryLabel, - categoryValue), - BenthosBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, - thisIndex); - } - - return result; - } - - public BatchContainer<MarineLitterBatch> getComputedMarineLitterBatches(FishingOperation operation, - Float marineLitterweight) { - - String fishingOperationId = operation.getId(); - BatchContainer<MarineLitterBatch> rootMarineLitterBatch = - persistenceService.getRootMarineLitterBatch(fishingOperationId); - - if (rootMarineLitterBatch != null) { - boolean checkWeight = marineLitterweight == null; - - List<MarineLitterBatch> children = rootMarineLitterBatch.getChildren(); - for (int i = 0; i < children.size(); i++) { - MarineLitterBatch batch = children.get(i); - if (checkWeight && batch.getWeight() == null) { - throw new TuttiWeightComputingException( - _("tutti.validator.warning.marineLitter.weight.required"), - MarineLitterBatch.PROPERTY_WEIGHT, - i); - } - } - } - - return rootMarineLitterBatch; - } -} Modified: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/ValidateCruiseOperationsService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/ValidateCruiseOperationsService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/ValidateCruiseOperationsService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -39,6 +39,7 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; +import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocols; import fr.ifremer.tutti.persistence.entities.referential.Species; @@ -48,6 +49,7 @@ import fr.ifremer.tutti.service.TuttiDataContext; import fr.ifremer.tutti.service.TuttiServiceContext; import fr.ifremer.tutti.service.ValidationService; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -76,7 +78,7 @@ protected ValidationService validationService; - protected TuttiWeightComputingService tuttiWeightComputingService; + protected WeightComputingService weightComputingService; protected DecoratorService decoratorService; @@ -87,7 +89,7 @@ super.setServiceContext(context); persistenceService = getService(PersistenceService.class); validationService = getService(ValidationService.class); - tuttiWeightComputingService = getService(TuttiWeightComputingService.class); + weightComputingService = getService(WeightComputingService.class); decoratorService = getService(DecoratorService.class); sampleCategoryModel = context.getSampleCategoryModel(); } @@ -143,8 +145,8 @@ } /** - * @param file - * @param validationResults + * @param file where to write result + * @param validationResults result of validation */ public void exportValidationResults(File file, Map<FishingOperation, NuitonValidatorResult> validationResults) { try { @@ -161,9 +163,9 @@ } /** - * @param file - * @param operation - * @param validationResult + * @param file where to write result + * @param operation operation to check + * @param validationResult result of validation */ public void exportValidationResult(File file, FishingOperation operation, NuitonValidatorResult validationResult) { try { @@ -226,7 +228,7 @@ * Adds additional messages to the validation results * * @param fishingOperation the operation to validate - * @param fishingOperation the catchBatch to validate + * @param catchBatch the catchBatch to validate * @param validator the validatpr containing the messages. */ protected void checkOperation(FishingOperation fishingOperation, @@ -251,7 +253,7 @@ for (SpeciesBatch batch : roots) { try { - tuttiWeightComputingService.computeSpeciesBatch(batch); + weightComputingService.computeSpeciesBatch(batch); } catch (TuttiBusinessException e) { errors.add(e.getMessage()); @@ -274,7 +276,7 @@ for (BenthosBatch batch : roots) { try { - rootBenthosBatch = tuttiWeightComputingService.getComputedBenthosBatches(fishingOperation); + weightComputingService.computeBenthosBatch(batch); } catch (TuttiBusinessException e) { errors.add(e.getMessage()); @@ -290,7 +292,7 @@ BatchContainer<MarineLitterBatch> rootMarineLitterBatch; try { Float weight = catchBatch == null ? null : catchBatch.getMarineLitterTotalWeight(); - rootMarineLitterBatch = tuttiWeightComputingService.getComputedMarineLitterBatches(fishingOperation, weight); + rootMarineLitterBatch = weightComputingService.getComputedMarineLitterBatches(fishingOperation, weight); } catch (TuttiBusinessException e) { errors.add(e.getMessage()); @@ -299,7 +301,7 @@ try { if (catchBatch != null) { - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, + weightComputingService.computeCatchBatchWeights(catchBatch, rootSpeciesBatch, rootBenthosBatch, rootMarineLitterBatch); @@ -314,16 +316,16 @@ TuttiDataContext dataContext = context.getDataContext(); if (dataContext.isProtocolFilled()) { - TuttiProtocol protocol = dataContext.getProtocol(); +// TuttiProtocol protocol = dataContext.getProtocol(); Map<String, List<String>> warningMap = Maps.newHashMap(); Decorator<Species> speciesDecorator = decoratorService.getDecoratorByType(Species.class); if (rootSpeciesBatch != null) { for (SpeciesBatch batch : rootSpeciesBatch.getChildren()) { - if (isSpeciesBatchInvalid(batch, protocol)) { + if (isSpeciesBatchInvalid(batch)) { String species = speciesDecorator.toString(batch.getSpecies()); String categoryValue = decoratorService.getDecorator(batch.getSampleCategoryValue()) - .toString(batch.getSampleCategoryValue()); + .toString(batch.getSampleCategoryValue()); warningMap.put("species", Lists.newArrayList(_("tutti.validator.warning.species.protocolNotRespected", species, categoryValue))); @@ -334,7 +336,7 @@ if (rootBenthosBatch != null) { for (BenthosBatch batch : rootBenthosBatch.getChildren()) { - if (isBenthosBatchInvalid(batch, protocol)) { + if (isBenthosBatchInvalid(batch)) { String species = speciesDecorator.toString(batch.getSpecies()); String categoryValue = decoratorService.getDecorator(batch.getSampleCategoryValue()) .toString(batch.getSampleCategoryValue()); @@ -353,19 +355,53 @@ /** * Is the species batch respecting the protocol recommendations? * - * @param batch the batch to check - * @param protocol the current protocol + * @param batch the batch to check (it should be a leaf) + * @param frequencies the frequencies of the batch + * @return true if the batch respects the protocol, false otherwise + */ + public boolean isSpeciesBatchValid(SpeciesBatch batch, + List<SpeciesBatchFrequency> frequencies) { + boolean result = true; + + TuttiProtocol protocol = persistenceService.getProtocol(); + + if (protocol != null) { + Species species = batch.getSpecies(); + List<SpeciesProtocol> speciesProtocols = protocol.getSpecies(); + SpeciesProtocol speciesProtocol = TuttiProtocols.getSpeciesProtocol(species, speciesProtocols); + + if (speciesProtocol != null) { + List<Integer> mandatoryCategories = speciesProtocol.getMandatorySampleCategoryId(); + + SpeciesBatch browsingBatch = batch; + while (browsingBatch.getParentBatch() != null) { + mandatoryCategories.remove(browsingBatch.getSampleCategoryId()); + browsingBatch = browsingBatch.getParentBatch(); + } + result = mandatoryCategories.isEmpty() && + (!speciesProtocol.isCountIfNoFrequencyEnabled() + || CollectionUtils.isNotEmpty(frequencies) + || batch.getNumber() != null); + } + } + return result; + } + + /** + * Is the species batch respecting the protocol recommendations? + * + * @param batch the batch to check * @return true if the batch or one of its children does not respect the protocol, false otherwise */ - protected boolean isSpeciesBatchInvalid(SpeciesBatch batch, TuttiProtocol protocol) { + protected boolean isSpeciesBatchInvalid(SpeciesBatch batch) { if (batch.isChildBatchsEmpty()) { List<SpeciesBatchFrequency> frequencies = persistenceService.getAllSpeciesBatchFrequency(batch.getId()); - return !TuttiProtocols.isSpeciesBatchValid(protocol, batch, frequencies); + return !isSpeciesBatchValid(batch, frequencies); } for (SpeciesBatch child : batch.getChildBatchs()) { - boolean invalid = isSpeciesBatchInvalid(child, protocol); + boolean invalid = isSpeciesBatchInvalid(child); if (invalid) { return true; } @@ -376,22 +412,20 @@ /** * Is the benthos batch respecting the protocol recommendations? * - * @param batch the batch to check - * @param protocol the current protocol + * @param batch the batch to check * @return true if the batch or one of its children does not respect the protocol, false otherwise */ - protected boolean isBenthosBatchInvalid(BenthosBatch batch, TuttiProtocol protocol) { + protected boolean isBenthosBatchInvalid(BenthosBatch batch) { if (batch.isChildBatchsEmpty()) { List<BenthosBatchFrequency> frequencies = persistenceService.getAllBenthosBatchFrequency(batch.getId()); - return !TuttiProtocols.isBenthosBatchValid( - protocol, - batch, - frequencies); + return !isBenthosBatchValid( + batch, + frequencies); } for (BenthosBatch child : batch.getChildBatchs()) { - boolean invalid = isBenthosBatchInvalid(child, protocol); + boolean invalid = isBenthosBatchInvalid(child); if (invalid) { return true; } @@ -400,8 +434,8 @@ } /** - * @param operation - * @param validationResult + * @param operation option to check + * @param validationResult result of validation */ protected List<String> getExportLines(FishingOperation operation, NuitonValidatorResult validationResult) { List<String> lines = Lists.newArrayList(); @@ -421,4 +455,42 @@ return lines; } + /** + * Is the benthos batch respecting the protocol recommendations? + * + * @param batch the batch to check (it should be a leaf) + * @param frequencies the frequencies of the batch + * @return true if the batch respects the protocol, false otherwise + */ + public boolean isBenthosBatchValid(BenthosBatch batch, + List<BenthosBatchFrequency> frequencies) { + + TuttiProtocol protocol = persistenceService.getProtocol(); + + boolean result = true; + + if (protocol != null) { + Species species = batch.getSpecies(); + List<SpeciesProtocol> speciesProtocols = protocol.getBenthos(); + SpeciesProtocol speciesProtocol = TuttiProtocols.getSpeciesProtocol(species, speciesProtocols); + + if (speciesProtocol != null) { + // get the categories which should be set + List<Integer> mandatoryCategories = + speciesProtocol.getMandatorySampleCategoryId(); + + BenthosBatch browsingBatch = batch; + while (browsingBatch.getParentBatch() != null) { + mandatoryCategories.remove(browsingBatch.getSampleCategoryId()); + browsingBatch = browsingBatch.getParentBatch(); + } + result = mandatoryCategories.isEmpty() && + (!speciesProtocol.isCountIfNoFrequencyEnabled() + || CollectionUtils.isNotEmpty(frequencies) + || batch.getNumber() != null); + } + } + return result; + } + } Added: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightCleaningService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightCleaningService.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightCleaningService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,558 @@ +package fr.ifremer.tutti.service.catches; + +import com.google.common.base.Preconditions; +import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Multimap; +import com.google.common.collect.Sets; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatchFrequency; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; +import fr.ifremer.tutti.persistence.entities.data.SpeciesAbleBatch; +import fr.ifremer.tutti.persistence.entities.data.SpeciesAbleBatchFrequency; +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.service.AbstractTuttiService; +import fr.ifremer.tutti.service.DecoratorService; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.TuttiServiceContext; +import fr.ifremer.tutti.service.WeightUnit; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static fr.ifremer.tutti.service.PersistenceService.FrequencyFunction; +import static org.nuiton.i18n.I18n._; + +/** + * A service to check and clean species and benthos batches redundant weights. + * <p/> + * Created on 9/27/13. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 2.6 + */ +public class WeightCleaningService extends AbstractTuttiService { + + private static final Log log = + LogFactory.getLog(WeightCleaningService.class); + + protected PersistenceService persistenceService; + + protected DecoratorService decoratorService; + + protected SampleCategoryModel sampleCategoryModel; + + protected FrequencyFunction<SpeciesBatch, SpeciesBatchFrequency> speciesFrequencyFunction; + + protected FrequencyFunction<BenthosBatch, BenthosBatchFrequency> benthosFrequencyFunction; + + protected WeightUnit benthosWeightUnit; + + protected WeightUnit speciesWeightUnit; + + private String speciesBatchPrefix; + + private String benthosBatchPrefix; + + @Override + public void setServiceContext(TuttiServiceContext context) { + super.setServiceContext(context); + persistenceService = getService(PersistenceService.class); + decoratorService = getService(DecoratorService.class); + sampleCategoryModel = context.getSampleCategoryModel(); + speciesFrequencyFunction = persistenceService.newSpeciesFrequenciesFunction(); + benthosFrequencyFunction = persistenceService.newBenthosFrequenciesFunction(); + benthosWeightUnit = context.getConfig().getBenthosWeightUnit(); + speciesWeightUnit = context.getConfig().getSpeciesWeightUnit(); + speciesBatchPrefix = _("tutti.service.operations.cleanWeights.species.batch"); + benthosBatchPrefix = _("tutti.service.operations.cleanWeights.benthos.batch"); + } + + /** + * Check if there is some redundant weights that could be cleaned. + * <p/> + * If no warning found, then return is a empty map, otherwise all errors + * for any bad fishing operation. + * <p/> + * Result keys are fishing operation id, values are all batches in error for + * the fishing operation. + * + * @param cruiseId id of the cruise to check. + * @return map of warnings, or empty map if no error found. + */ + public Map<String, String> checkCruise(String cruiseId) { + + if (log.isDebugEnabled()) { + log.debug("Will check cruise: " + cruiseId); + } + + Map<String, String> result = Maps.newLinkedHashMap(); + + List<FishingOperation> allFishingOperation = + persistenceService.getAllFishingOperation(cruiseId); + + for (FishingOperation fishingOperation : allFishingOperation) { + + String fishingOperationId = fishingOperation.getId(); + + boolean withCatchBatch = + persistenceService.isFishingOperationWithCatchBatch( + fishingOperationId); + + if (!withCatchBatch) { + if (log.isWarnEnabled()) { + log.warn("Skip fishing operation " + fishingOperation + + " since no catchBatch associated."); + } + continue; + } + + Multimap<String, String> errors = checkFishingOperation(fishingOperationId); + + if (!errors.isEmpty()) { + result.put(fishingOperationId, errorsToString(errors)); + } + } + return result; + } + + public String errorsToString(Multimap<String, String> errors) { + StringBuilder errorsStr = new StringBuilder("<ul style=\"font-size:11\">"); + for (String error : errors.keySet()) { + + errorsStr.append("<li>"); + Collection<String> strings = errors.get(error); + errorsStr.append(error); + if (strings.size() == 1) { + errorsStr.append(" ").append(strings.iterator().next()); + } else { + errorsStr.append("<ul>"); + for (String s : strings) { + errorsStr.append("<li>"); + errorsStr.append(s); + errorsStr.append("</li>"); + } + errorsStr.append("</ul>"); + } + errorsStr.append("</li>"); + } + errorsStr.append("</ul>"); + + return errorsStr.toString(); + } + + /** + * Clean all redundant weights for the given cruise. + * + * @param cruiseId id of the cruise to clean. + */ + public void cleanCruise(String cruiseId) { + + if (log.isDebugEnabled()) { + log.debug("Will clean cruise: " + cruiseId); + } + + List<FishingOperation> allFishingOperation = + persistenceService.getAllFishingOperation(cruiseId); + + for (FishingOperation fishingOperation : allFishingOperation) { + + String fishingOperationId = fishingOperation.getId(); + + cleanFishingOperation(fishingOperationId); + } + } + + /** + * Check for some redundant weights in species or benthos batches of + * the given operation. + * + * @param fishingOperationId id of the fishing operation to check + * @return the list of all species / benthos which contains a redundant weight + */ + public Multimap<String, String> checkFishingOperation(String fishingOperationId) { + + if (log.isDebugEnabled()) { + log.debug("Will check fishingOperation: " + fishingOperationId); + } + Multimap<String, String> result = LinkedHashMultimap.create(); + + boolean withCatchBatch = + persistenceService.isFishingOperationWithCatchBatch( + fishingOperationId); + + if (withCatchBatch) { + + // check species batches + + BatchContainer<SpeciesBatch> speciesBatch = + persistenceService.getRootSpeciesBatch( + fishingOperationId, sampleCategoryModel); + + for (SpeciesBatch batch : speciesBatch.getChildren()) { + + checkBatch( + speciesBatchPrefix, + speciesWeightUnit, + batch, + result, + speciesFrequencyFunction); + } + + // check benthos batches + + BatchContainer<BenthosBatch> benthosBatch = + persistenceService.getRootBenthosBatch( + fishingOperationId, sampleCategoryModel); + + for (BenthosBatch batch : benthosBatch.getChildren()) { + + checkBatch(benthosBatchPrefix, + benthosWeightUnit, + batch, + result, + benthosFrequencyFunction); + } + } else { + + // no catch, no check + + if (log.isWarnEnabled()) { + log.warn("Skip fishing operation " + fishingOperationId + + " since no catchBatch associated."); + } + } + + return result; + } + + /** + * Clean all the redundant weights in species or benthos batches of + * the given operation. + * + * @param fishingOperationId id of the fishing operation to check + */ + public void cleanFishingOperation(String fishingOperationId) { + + if (log.isDebugEnabled()) { + log.debug("Will clean fishingOperation: " + fishingOperationId); + } + + boolean withCatchBatch = + persistenceService.isFishingOperationWithCatchBatch( + fishingOperationId); + + if (withCatchBatch) { + + // clean species batches + + Set<SpeciesBatch> speciesToSave = Sets.newHashSet(); + BatchContainer<SpeciesBatch> speciesBatch = + persistenceService.getRootSpeciesBatch( + fishingOperationId, sampleCategoryModel); + + for (SpeciesBatch batch : speciesBatch.getChildren()) { + + cleanBatch(speciesBatchPrefix, + speciesWeightUnit, + batch, + speciesToSave, + speciesFrequencyFunction); + } + + // clean benthos batches + + Set<BenthosBatch> benthosToSave = Sets.newHashSet(); + BatchContainer<BenthosBatch> benthosBatch = + persistenceService.getRootBenthosBatch( + fishingOperationId, sampleCategoryModel); + + for (BenthosBatch batch : benthosBatch.getChildren()) { + + cleanBatch(benthosBatchPrefix, + benthosWeightUnit, + batch, + benthosToSave, + benthosFrequencyFunction); + } + + if (!(speciesToSave.isEmpty() && speciesToSave.isEmpty())) { + + // save modified batches + + FishingOperation fishingOperation = + persistenceService.getFishingOperation(fishingOperationId); + + for (SpeciesBatch toSave : speciesToSave) { + toSave.setFishingOperation(fishingOperation); + persistenceService.saveSpeciesBatch(toSave); + } + + for (BenthosBatch toSave : benthosToSave) { + toSave.setFishingOperation(fishingOperation); + persistenceService.saveBenthosBatch(toSave); + } + } + + } else { + + // no catch, no clean + + if (log.isWarnEnabled()) { + log.warn("Skip fishing operation " + fishingOperationId + + " since no catchBatch associated."); + } + } + } + + protected <B extends SpeciesAbleBatch, F extends SpeciesAbleBatchFrequency> void checkBatch(String batchPrefix, + WeightUnit weightUnit, + B batch, + Multimap<String, String> result, + FrequencyFunction<B, F> frequencyFunction) { + + if (!batch.isChildBatchsEmpty()) { + + // check childs + for (SpeciesAbleBatch child : batch.getChildBatchs()) { + + B childBatch = (B) child; + + // check batch sample category weight (before childs) + String message = checkSampleCategoryWeightRedundant(weightUnit, batch, childBatch); + + if (message != null) { + + String label = getBatchLabel(batchPrefix, weightUnit, childBatch); + if (log.isInfoEnabled()) { + log.info(label + " " + message); + } + if (!result.containsEntry(label, message)) { + result.put(label, message); + } + } + + // check childs + checkBatch(batchPrefix, weightUnit, childBatch, result, frequencyFunction); + } + } else { + + { // check batch weight + String message = checkWeightRedundant(weightUnit, batch); + + if (message != null) { + String label = getBatchLabel(batchPrefix, weightUnit, batch); + if (log.isInfoEnabled()) { + log.info(label + " " + message); + } + if (!result.containsEntry(label, message)) { + result.put(label, message); + } + } + } + + { // check batch frequencies weight + String message = checkFrequencyWeightRedundant(weightUnit, batch, frequencyFunction); + + if (message != null) { + String label = getBatchLabel(batchPrefix, weightUnit, batch); + if (log.isInfoEnabled()) { + log.info(label + " " + message); + } + if (!result.containsEntry(label, message)) { + result.put(label, message); + } + } + } + } + } + + protected <B extends SpeciesAbleBatch, F extends SpeciesAbleBatchFrequency> void cleanBatch(String batchPrefix, + WeightUnit weightUnit, + B batch, + Set<B> result, + FrequencyFunction<B, F> frequencyFunction) { + + if (!batch.isChildBatchsEmpty()) { + + // check childs + for (SpeciesAbleBatch child : batch.getChildBatchs()) { + + B childBatch = (B) child; + + // check batch sample category weight + String message = checkSampleCategoryWeightRedundant(weightUnit, batch, childBatch); + + // clean childs before + cleanBatch(batchPrefix, weightUnit, childBatch, result, frequencyFunction); + + if (message != null) { + + // always clean after cleaning childs + String label = getBatchLabel(batchPrefix, weightUnit, childBatch); + if (log.isInfoEnabled()) { + log.info(label + " " + message); + } + childBatch.setSampleCategoryWeight(null); + result.add(childBatch); + } + } + } else { + + boolean removeWeight = false; + + { // check batch frequencies weight + String message = checkFrequencyWeightRedundant(weightUnit, batch, frequencyFunction); + + if (message != null) { + String label = getBatchLabel(batchPrefix, weightUnit, batch); + if (log.isInfoEnabled()) { + log.info(label + " " + message); + } + removeWeight = true; + + } + } + + { // check batch weight + String message = checkWeightRedundant(weightUnit, batch); + + if (message != null) { + String label = getBatchLabel(batchPrefix, weightUnit, batch); + if (log.isInfoEnabled()) { + log.info(label + " " + message); + } + removeWeight = true; + } + } + + if (removeWeight) { + + // must clean the batch weight + batch.setWeight(null); + result.add(batch); + } + } + } + + protected String checkSampleCategoryWeightRedundant(WeightUnit weightUnit, + SpeciesAbleBatch parentBatch, + SpeciesAbleBatch batch) { + + Preconditions.checkNotNull(parentBatch); + + String result = null; + if (parentBatch != null) { + + // check the sample weight is different than his parent one + Float sampleCategoryWeight = batch.getSampleCategoryWeight(); + Float parentSampleCategoryWeight = parentBatch.getSampleCategoryWeight(); + + if (sampleCategoryWeight != null && ObjectUtils.equals(parentSampleCategoryWeight, sampleCategoryWeight)) { + + result = _( + "tutti.service.operations.cleanWeights.error.redundant.sampleCategoryWeight", + weightUnit.fromEntity(sampleCategoryWeight), + weightUnit.getShortLabel(), + getCategoryLabel(batch), + getCategoryLabel(parentBatch) + ); + + } + } + return result; + } + + + protected <B extends SpeciesAbleBatch, F extends SpeciesAbleBatchFrequency> String checkFrequencyWeightRedundant(WeightUnit weightUnit, + B batch, + FrequencyFunction<B, F> frequencyFunction) { + Preconditions.checkState(batch.isChildBatchsEmpty()); + + String result = null; + + // on a leaf, check if weight is not = to sum of frequencies weight + Float weight = batch.getWeight(); + if (weight != null) { + + // check if there is some frequencies + List<F> frequencies = frequencyFunction.apply(batch); + Float frequenciesWeigth = + persistenceService.countFrequenciesWeight(frequencies, true); + + if (ObjectUtils.equals(weight, frequenciesWeigth)) { + result = _( + "tutti.service.operations.cleanWeights.error.redundant.frequencyWeight", + weightUnit.fromEntity(weight), + weightUnit.getShortLabel(), + getCategoryLabel(batch)); + } + } + + return result; + } + + protected String checkWeightRedundant(WeightUnit weightUnit, + SpeciesAbleBatch batch) { + + Preconditions.checkState(batch.isChildBatchsEmpty()); + + String result = null; + + // on a leaf, check if weight is not = to the finest category weight + Float weight = batch.getWeight(); + Float sampleCategoryWeight = batch.getSampleCategoryWeight(); + if (weight != null && ObjectUtils.equals(weight, sampleCategoryWeight)) { + + result = _( + "tutti.service.operations.cleanWeights.error.redundant.weight", + weightUnit.fromEntity(weight), + weightUnit.getShortLabel(), + getCategoryLabel(batch)); + } + + return result; + } + + protected String getBatchLabel(String type, WeightUnit weightUnit, + SpeciesAbleBatch batch) { + StringBuilder sb = new StringBuilder("[ " + type); + + String species = decoratorService.getDecoratorByType(Species.class).toString(batch.getSpecies()); + sb.append(" ").append(species); + + List<String> categories = Lists.newArrayList(); + SpeciesAbleBatch b = batch; + while (b.getParentBatch() != null) { + String categoryValue = decoratorService.getDecorator(b.getSampleCategoryValue()) + .toString(b.getSampleCategoryValue()); + categories.add(0, categoryValue + " / " + weightUnit.fromEntity(b.getSampleCategoryWeight())); + b = b.getParentBatch(); + } + + for (String category : categories) { + sb.append(" - ").append(category); + } + sb.append(" ]"); + return sb.toString(); + } + + protected String getCategoryLabel(SpeciesAbleBatch batch) { + SampleCategoryModelEntry category = + sampleCategoryModel.getCategoryById(batch.getSampleCategoryId()); + String result = category.getLabel(); + return result; + } + +} Property changes on: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightCleaningService.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Copied: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightComputingService.java (from rev 1246, trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingService.java) =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightComputingService.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/WeightComputingService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,757 @@ +package fr.ifremer.tutti.service.catches; + +/* + * #%L + * Tutti :: Service + * $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.TuttiBusinessException; +import fr.ifremer.tutti.persistence.entities.TuttiEntities; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatchFrequency; +import fr.ifremer.tutti.persistence.entities.data.CatchBatch; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; +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.service.AbstractTuttiService; +import fr.ifremer.tutti.service.DecoratorService; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.TuttiServiceContext; +import fr.ifremer.tutti.service.ValidationService; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorResult; + +import java.util.List; +import java.util.Map; + +import static org.nuiton.i18n.I18n._; + +/** + * @author kmorin <kmorin@codelutin.com> + * @since 1.3 + */ +public class WeightComputingService extends AbstractTuttiService { + + private static final Log log = + LogFactory.getLog(WeightComputingService.class); + + protected PersistenceService persistenceService; + + protected ValidationService validationService; + + protected DecoratorService decoratorService; + + protected SampleCategoryModel sampleCategoryModel; + + @Override + public void setServiceContext(TuttiServiceContext context) { + super.setServiceContext(context); + persistenceService = getService(PersistenceService.class); + validationService = getService(ValidationService.class); + decoratorService = getService(DecoratorService.class); + sampleCategoryModel = context.getSampleCategoryModel(); + } + + /** + * To check if can compute for any fishing operation of the cruise given + * by his id. + * <p/> + * If no error found, then return is a empty map, otherwise the first error + * found for any bad fishing operation. + * <p/> + * Result keys are fishing operation id, values the first error for + * the fishing operation. + * + * @param cruiseId id of the cruise to check. + * @return map of errors, or empty map if no error found. + * @since 1.4 + */ + public Map<String, String> checkCruise(String cruiseId) { + + if (log.isDebugEnabled()) { + log.debug("Will check cruise: " + cruiseId); + } + Map<String, String> result = Maps.newTreeMap(); + + List<FishingOperation> allFishingOperation = + persistenceService.getAllFishingOperation(cruiseId); + + for (FishingOperation fishingOperation : allFishingOperation) { + + String fishingOperationId = fishingOperation.getId(); + + boolean withCatchBatch = + persistenceService.isFishingOperationWithCatchBatch( + fishingOperationId); + + if (!withCatchBatch) { + if (log.isWarnEnabled()) { + log.warn("Skip fishing operation " + fishingOperation + + " since no catchBatch associated."); + } + continue; + } + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(fishingOperationId); + + BatchContainer<SpeciesBatch> rootSpeciesBatch; + try { + rootSpeciesBatch = getComputedSpeciesBatches(fishingOperation); + + } catch (TuttiBusinessException e) { + result.put(fishingOperationId, e.getMessage()); + rootSpeciesBatch = persistenceService.getRootSpeciesBatch(fishingOperationId, null); + } + + BatchContainer<BenthosBatch> rootBenthosBatch; + try { + rootBenthosBatch = getComputedBenthosBatches(fishingOperation); + + } catch (TuttiBusinessException e) { + result.put(fishingOperationId, e.getMessage()); + rootBenthosBatch = persistenceService.getRootBenthosBatch(fishingOperationId, null); + } + + BatchContainer<MarineLitterBatch> rootMarineLitterBatch; + try { + Float weight = catchBatch == null ? null : catchBatch.getMarineLitterTotalWeight(); + rootMarineLitterBatch = getComputedMarineLitterBatches(fishingOperation, weight); + + } catch (TuttiBusinessException e) { + result.put(fishingOperationId, e.getMessage()); + rootMarineLitterBatch = persistenceService.getRootMarineLitterBatch(fishingOperationId); + } + + try { + if (catchBatch != null) { + computeCatchBatchWeights(catchBatch, + rootSpeciesBatch, + rootBenthosBatch, + rootMarineLitterBatch); + } + } catch (TuttiBusinessException e) { + result.put(fishingOperationId, e.getMessage()); + } + } + return result; + } + + /** + * Compute the weights of the catch batch (not the ones of the species, benthos nor marine litter batches) + * + * @param catchBatch the catch batch with the weights to compute + * @param rootSpeciesBatch the species batches with already computed weights + * @param rootBenthosBatch the benthos batches with already computed weights + * @param rootMarineLitterBatch the marine litter batches with already computed weights + */ + public void computeCatchBatchWeights(CatchBatch catchBatch, + BatchContainer<SpeciesBatch> rootSpeciesBatch, + BatchContainer<BenthosBatch> rootBenthosBatch, + BatchContainer<MarineLitterBatch> rootMarineLitterBatch) { + + // Species + Float speciesTotalComputedSortedWeight = 0f; + Float speciesTotalComputedUnsortedWeight = 0f; + + if (rootSpeciesBatch != null) { + for (int i = 0; i < rootSpeciesBatch.getChildren().size(); i++) { + SpeciesBatch row = rootSpeciesBatch.getChildren().get(i); + Float weight = TuttiEntities.getValueOrComputedValue( + row.getSampleCategoryWeight(), + row.getSampleCategoryComputedWeight()); + if (weight == null) { + break; + } + + if (persistenceService.isVracSpeciesBatch(row)) { + speciesTotalComputedSortedWeight += weight; + } else { + speciesTotalComputedUnsortedWeight += weight; + } + } + } + + Number inertWeight = catchBatch.getSpeciesTotalInertWeight(); + if (inertWeight != null) { + speciesTotalComputedSortedWeight += inertWeight.floatValue(); + } else { + catchBatch.setSpeciesTotalInertComputedWeight(0f); + } + + Number livingNotItemizedWeight = catchBatch.getSpeciesTotalLivingNotItemizedWeight(); + if (livingNotItemizedWeight != null) { + speciesTotalComputedSortedWeight += livingNotItemizedWeight.floatValue(); + } else { + catchBatch.setSpeciesTotalLivingNotItemizedComputedWeight(0f); + } + + catchBatch.setSpeciesTotalSampleSortedComputedWeight(speciesTotalComputedSortedWeight); + + Float speciesTotalSortedWeight = catchBatch.getSpeciesTotalSortedWeight(); + if (speciesTotalSortedWeight == null) { + speciesTotalSortedWeight = speciesTotalComputedSortedWeight; + catchBatch.setSpeciesTotalSortedComputedWeight(speciesTotalSortedWeight); + + } else if (speciesTotalSortedWeight < speciesTotalComputedSortedWeight) { + throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.species.incoherentTotalSorted")); + } + catchBatch.setSpeciesTotalUnsortedComputedWeight(speciesTotalComputedUnsortedWeight); + + if (speciesTotalSortedWeight == null) { + speciesTotalSortedWeight = catchBatch.getSpeciesTotalSortedComputedWeight(); + } + Float speciesTotalWeight = speciesTotalComputedUnsortedWeight + speciesTotalSortedWeight; + catchBatch.setSpeciesTotalComputedWeight(speciesTotalWeight); + + // Benthos + Float benthosTotalComputedSortedWeight = 0f; + Float benthosTotalComputedUnsortedWeight = 0f; + + if (rootBenthosBatch != null) { + for (int i = 0; i < rootBenthosBatch.getChildren().size(); i++) { + BenthosBatch row = rootBenthosBatch.getChildren().get(i); + Float weight = TuttiEntities.getValueOrComputedValue( + row.getSampleCategoryWeight(), + row.getSampleCategoryComputedWeight()); + if (weight == null) { + break; + } + + if (persistenceService.isVracBenthosBatch(row)) { + benthosTotalComputedSortedWeight += weight; + } else { + benthosTotalComputedUnsortedWeight += weight; + } + } + } + + inertWeight = catchBatch.getBenthosTotalInertWeight(); + if (inertWeight != null) { + benthosTotalComputedSortedWeight += inertWeight.floatValue(); + } else { + catchBatch.setBenthosTotalInertComputedWeight(0f); + } + + livingNotItemizedWeight = catchBatch.getBenthosTotalLivingNotItemizedWeight(); + if (livingNotItemizedWeight != null) { + benthosTotalComputedSortedWeight += livingNotItemizedWeight.floatValue(); + } else { + catchBatch.setBenthosTotalLivingNotItemizedComputedWeight(0f); + } + + catchBatch.setBenthosTotalSampleSortedComputedWeight(benthosTotalComputedSortedWeight); + + Float benthosTotalSortedWeight = catchBatch.getBenthosTotalSortedWeight(); + if (benthosTotalSortedWeight == null) { + benthosTotalSortedWeight = benthosTotalComputedSortedWeight; + catchBatch.setBenthosTotalSortedComputedWeight(benthosTotalSortedWeight); + + } else if (benthosTotalSortedWeight < benthosTotalComputedSortedWeight) { + throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.benthos.incoherentTotalSorted")); + } + catchBatch.setBenthosTotalUnsortedComputedWeight(benthosTotalComputedUnsortedWeight); + + if (benthosTotalSortedWeight == null) { + benthosTotalSortedWeight = catchBatch.getBenthosTotalSortedComputedWeight(); + } + Float benthosTotalWeight = benthosTotalComputedUnsortedWeight + benthosTotalSortedWeight; + catchBatch.setBenthosTotalComputedWeight(benthosTotalWeight); + + // Marine litter + Float marineLitterTotalComputedWeight = 0f; + + if (rootMarineLitterBatch != null) { + for (int i = 0; i < rootMarineLitterBatch.getChildren().size(); i++) { + MarineLitterBatch row = rootMarineLitterBatch.getChildren().get(i); + Float rowWeight = row.getWeight(); + if (rowWeight == null) { + marineLitterTotalComputedWeight = null; + break; + } + marineLitterTotalComputedWeight += rowWeight; + } + } + catchBatch.setMarineLitterTotalComputedWeight(marineLitterTotalComputedWeight); + + Float marineLitterTotalWeight = catchBatch.getMarineLitterTotalWeight(); + if (marineLitterTotalWeight == null) { + marineLitterTotalWeight = marineLitterTotalComputedWeight; + + } else if (marineLitterTotalComputedWeight != null && marineLitterTotalWeight < marineLitterTotalComputedWeight) { + throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.marineLitter.incoherentTotal")); + } + // nothing to do with the marine litter weight, it is an isolated weight + + // Catch + Float totalUnsortedWeight = catchBatch.getSpeciesTotalUnsortedComputedWeight() + + catchBatch.getBenthosTotalUnsortedComputedWeight(); + + Float totalSortedWeight = speciesTotalSortedWeight + benthosTotalSortedWeight; + + catchBatch.setCatchTotalSortedComputedWeight(totalSortedWeight); + catchBatch.setCatchTotalUnsortedComputedWeight(totalUnsortedWeight); + + Float totalWeight = catchBatch.getCatchTotalWeight(); + Float rejectedWeight = catchBatch.getCatchTotalRejectedWeight(); + + if (rejectedWeight == null && totalWeight != null) { + if (!totalWeight.equals(totalUnsortedWeight + + totalSortedWeight)) { + throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.incoherentTotal")); + + } else { + catchBatch.setCatchTotalRejectedComputedWeight(totalWeight + - totalUnsortedWeight + - totalSortedWeight); + } + + } else if (totalWeight == null) { + if (rejectedWeight == null) { + rejectedWeight = 0f; + catchBatch.setCatchTotalRejectedComputedWeight(0f); + } + catchBatch.setCatchTotalComputedWeight(totalUnsortedWeight + + totalSortedWeight + + rejectedWeight); + + } else if (!totalWeight.equals(totalUnsortedWeight + totalSortedWeight + rejectedWeight)) { + throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.incoherentTotal")); + } + } + + private int currentSpeciesRowIndex; + + public BatchContainer<SpeciesBatch> getComputedSpeciesBatches(FishingOperation operation) { + + BatchContainer<SpeciesBatch> rootSpeciesBatch = null; + + if (persistenceService.isFishingOperationWithCatchBatch(operation.getId())) { + rootSpeciesBatch = persistenceService.getRootSpeciesBatch(operation.getId(), null); + + currentSpeciesRowIndex = 0; + if (rootSpeciesBatch != null) { + List<SpeciesBatch> roots = rootSpeciesBatch.getChildren(); + + for (SpeciesBatch batch : roots) { + computeSpeciesBatch(batch); + } + } + } + + return rootSpeciesBatch; + } + + protected String getCategoryLabel(Integer sampleCategoryId) { + SampleCategoryModelEntry category = + sampleCategoryModel.getCategoryById(sampleCategoryId); + String result = category.getLabel(); + return result; + } + + public Float computeSpeciesBatch(SpeciesBatch batch) { + Float result = null; + int thisIndex = currentSpeciesRowIndex++; + Float categoryWeight = batch.getSampleCategoryWeight(); + Float rowWeight = batch.getWeight(); + String species = decoratorService.getDecoratorByType(Species.class).toString(batch.getSpecies()); + String categoryValue = decoratorService.getDecorator(batch.getSampleCategoryValue()) + .toString(batch.getSampleCategoryValue()); + + NuitonValidatorResult validation = validationService.validateSpeciesBatch(batch); + if (!validation.isValid()) { + List<String> messages = validation.getErrorMessages(SpeciesBatch.PROPERTY_WEIGHT); + String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); + throw new TuttiWeightComputingException(_(messages.get(0), + species, + categoryLabel, + categoryValue, + batch.getWeight(), + batch.getSampleCategoryWeight()), + SpeciesBatch.PROPERTY_WEIGHT, + thisIndex); + } + + List<SpeciesBatch> children = batch.getChildBatchs(); + // if the row is not a leaf + if (batch.sizeChildBatchs() > 0) { + Float sum = 0f; + // make the sum of the children weights + for (SpeciesBatch child : children) { + Float weight = computeSpeciesBatch(child); + if (weight == null) { + sum = null; + break; + } + sum += weight; + } + + if (sum != null) { + if (categoryWeight == null) { + batch.setSampleCategoryComputedWeight(sum); + + } else if (categoryWeight < sum) { + String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); + throw new TuttiWeightComputingException( + _("tutti.service.operations.computeWeights.error.species.incoherentParentCategoryWeight", + species, + categoryLabel, + categoryValue, + categoryWeight, + sum), + SpeciesBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, + thisIndex); + + } else { + sum = categoryWeight; + } + result = sum; + } + + } else {// the row is a leaf + + batch.setComputedWeight(null); + + List<SpeciesBatchFrequency> frequencies = persistenceService.getAllSpeciesBatchFrequency(batch.getId()); + + if (CollectionUtils.isNotEmpty(frequencies)) { + // if there are frequencies, then compute their weight + Float frequencyWeight = 0f; + for (SpeciesBatchFrequency frequency : frequencies) { + Float w = frequency.getWeight(); + if (w == null) { + + // can't sum when a null value appears + frequencyWeight = null; + break; + + } else if (frequencyWeight != null) { + + // still can sum weights + frequencyWeight += w; + } + } + + if (categoryWeight == null && rowWeight != null) { +// throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.incoherentRowWeightCategory")); + + } else if (rowWeight != null && frequencyWeight != null + && !rowWeight.equals(frequencyWeight)) { + + String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); + + throw new TuttiWeightComputingException( + _("tutti.service.operations.computeWeights.error.species.incoherentRowWeightFrequency", + species, + categoryLabel, + categoryValue, + frequencyWeight, + rowWeight), + SpeciesBatch.PROPERTY_WEIGHT, + thisIndex); + + } else if (categoryWeight == null && frequencyWeight != null) { + // if the category weight is null and the frequencies have a weight, + // then this weight is the result + batch.setSampleCategoryComputedWeight(frequencyWeight); + result = frequencyWeight; + + } else if (frequencyWeight != null + && !frequencyWeight.equals(categoryWeight)) { + + // if the weight of the frequencies is different from the category + // weight, then set the weight of the sample + if (frequencyWeight > categoryWeight) { + + String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); + + throw new TuttiWeightComputingException( + _("tutti.service.operations.computeWeights.error.species.incoherentCategoryWeight", + species, + categoryLabel, + categoryValue, + frequencyWeight, + categoryWeight), + SpeciesBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, + thisIndex); + + } else if (rowWeight == null) { + batch.setComputedWeight(frequencyWeight); + + } + result = categoryWeight; + + } else { + result = categoryWeight; + } + + // compute number from frequencies + Integer frequencyNumber = 0; + for (SpeciesBatchFrequency frequency : frequencies) { + Integer c = frequency.getNumber(); + frequencyNumber += c; + } + batch.setComputedNumber(frequencyNumber); + + } else { + result = categoryWeight; + } + } + if (result == null) { + + String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); + + throw new TuttiWeightComputingException( + _("tutti.service.operations.computeWeights.error.species.noWeight", + species, + categoryLabel, + categoryValue), + SpeciesBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, + thisIndex); + } + + return result; + } + + private int currentBenthosRowIndex; + + public BatchContainer<BenthosBatch> getComputedBenthosBatches(FishingOperation operation) { + + BatchContainer<BenthosBatch> rootBenthosBatch = null; + + if (persistenceService.isFishingOperationWithCatchBatch(operation.getId())) { + rootBenthosBatch = persistenceService.getRootBenthosBatch(operation.getId(), null); + + currentBenthosRowIndex = 0; + if (rootBenthosBatch != null) { + List<BenthosBatch> roots = rootBenthosBatch.getChildren(); + + for (BenthosBatch batch : roots) { + computeBenthosBatch(batch); + } + } + } + + return rootBenthosBatch; + } + + public Float computeBenthosBatch(BenthosBatch batch) { + Float result = null; + int thisIndex = currentBenthosRowIndex++; + Float categoryWeight = batch.getSampleCategoryWeight(); + Float rowWeight = batch.getWeight(); + String species = decoratorService.getDecoratorByType(Species.class).toString(batch.getSpecies()); + String categoryValue = decoratorService.getDecorator(batch.getSampleCategoryValue()) + .toString(batch.getSampleCategoryValue()); + + NuitonValidatorResult validation = validationService.validateBenthosBatch(batch); + if (!validation.isValid()) { + List<String> messages = validation.getErrorMessages(BenthosBatch.PROPERTY_WEIGHT); + + String categoryLabel = getCategoryLabel(batch.getSampleCategoryId()); + throw new TuttiWeightComputingException(_(messages.get(0), + species, + categoryLabel, + categoryValue, + batch.getWeight(), + batch.getSampleCategoryWeight()), + BenthosBatch.PROPERTY_WEIGHT, + thisIndex); + } + + List<BenthosBatch> children = batch.getChildBatchs(); + // if the row is not a leaf + if (!batch.isChildBatchsEmpty()) { + Float sum = 0f; + // make the sum of the children weights + for (BenthosBatch child : children) { + Float weight = computeBenthosBatch(child); + if (weight == null) { + sum = null; + break; + } + sum += weight; + } + + if (sum != null) { + if (categoryWeight == null) { + batch.setSampleCategoryComputedWeight(sum); + + } else if (categoryWeight < sum) { + String categoryLabel = + getCategoryLabel(batch.getSampleCategoryId()); + + throw new TuttiWeightComputingException( + _("tutti.service.operations.computeWeights.error.benthos.incoherentParentCategoryWeight", + species, + categoryLabel, + categoryValue, + categoryWeight, + sum), + BenthosBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, + thisIndex); + + } else { + sum = categoryWeight; + } + result = sum; + + } + + } else {// the row is a leaf + + batch.setComputedWeight(null); + + List<BenthosBatchFrequency> frequencies = persistenceService.getAllBenthosBatchFrequency(batch.getId()); + + if (CollectionUtils.isNotEmpty(frequencies)) { + // if there are frequencies, then compute their weight + Float frequencyWeight = 0f; + for (BenthosBatchFrequency frequency : frequencies) { + Float w = frequency.getWeight(); + if (w == null) { + + // can't sum when a null value appears + frequencyWeight = null; + break; + + } else if (frequencyWeight != null) { + + // still can sum weights + frequencyWeight += w; + } + } + + if (categoryWeight == null && rowWeight != null) { +// throw new TuttiBusinessException(_("tutti.service.operations.computeWeights.error.incoherentRowWeightCategory")); + + } else if (rowWeight != null && frequencyWeight != null + && !rowWeight.equals(frequencyWeight)) { + + String categoryLabel = + getCategoryLabel(batch.getSampleCategoryId()); + + throw new TuttiWeightComputingException( + _("tutti.service.operations.computeWeights.error.benthos.incoherentRowWeightFrequency", + species, + categoryLabel, + categoryValue, + rowWeight, + categoryWeight), + BenthosBatch.PROPERTY_WEIGHT, + thisIndex); + + } else if (categoryWeight == null && frequencyWeight != null) { + // if the category weight is null and the frequencies have a weight, + // then this weight is the result + batch.setSampleCategoryComputedWeight(frequencyWeight); + result = frequencyWeight; + + } else if (frequencyWeight != null + && !frequencyWeight.equals(categoryWeight)) { + + // if the weight of the frequencies is different from the category + // weight, then set the weight of the sample + if (frequencyWeight > categoryWeight) { + + String categoryLabel = + getCategoryLabel(batch.getSampleCategoryId()); + + throw new TuttiWeightComputingException( + _("tutti.service.operations.computeWeights.error.benthos.incoherentCategoryWeight", + species, + categoryLabel, + categoryValue, + frequencyWeight, + categoryWeight), + BenthosBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, + thisIndex); + + } else if (rowWeight == null) { + batch.setComputedWeight(frequencyWeight); + + } + result = categoryWeight; + + } else { + result = categoryWeight; + } + + // compute number from frequencies + Integer frequencyNumber = 0; + for (BenthosBatchFrequency frequency : frequencies) { + Integer c = frequency.getNumber(); + frequencyNumber += c; + } + batch.setComputedNumber(frequencyNumber); + } else { + result = categoryWeight; + } + } + if (result == null) { + + String categoryLabel = + getCategoryLabel(batch.getSampleCategoryId()); + + throw new TuttiWeightComputingException( + _("tutti.service.operations.computeWeights.error.benthos.noWeight", + species, + categoryLabel, + categoryValue), + BenthosBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT, + thisIndex); + } + + return result; + } + + public BatchContainer<MarineLitterBatch> getComputedMarineLitterBatches(FishingOperation operation, + Float marineLitterweight) { + + String fishingOperationId = operation.getId(); + BatchContainer<MarineLitterBatch> rootMarineLitterBatch = + persistenceService.getRootMarineLitterBatch(fishingOperationId); + + if (rootMarineLitterBatch != null) { + boolean checkWeight = marineLitterweight == null; + + List<MarineLitterBatch> children = rootMarineLitterBatch.getChildren(); + for (int i = 0; i < children.size(); i++) { + MarineLitterBatch batch = children.get(i); + if (checkWeight && batch.getWeight() == null) { + throw new TuttiWeightComputingException( + _("tutti.validator.warning.marineLitter.weight.required"), + MarineLitterBatch.PROPERTY_WEIGHT, + i); + } + } + } + + return rootMarineLitterBatch; + } +} Copied: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/MultiPostExportService.java (from rev 1246, trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportService.java) =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/MultiPostExportService.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/MultiPostExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,681 @@ +package fr.ifremer.tutti.service.catches.multipost; + +/* + * #%L + * Tutti :: Service + * $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 com.google.common.io.Files; +import fr.ifremer.tutti.TuttiIOUtil; +import fr.ifremer.tutti.TuttiTechnicalException; +import fr.ifremer.tutti.persistence.entities.CaracteristicMap; +import fr.ifremer.tutti.persistence.entities.data.AccidentalBatch; +import fr.ifremer.tutti.persistence.entities.data.AttachementObjectTypeEnum; +import fr.ifremer.tutti.persistence.entities.data.Attachment; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; +import fr.ifremer.tutti.persistence.entities.data.CatchBatch; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.IndividualObservationBatch; +import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; +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.service.AbstractTuttiService; +import fr.ifremer.tutti.service.DecoratorService; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.apache.commons.io.IOUtils; +import org.nuiton.csv.Export; +import org.nuiton.csv.ExportModel; + +import java.io.File; +import java.io.Writer; +import java.util.List; +import java.util.Map; + +import static org.nuiton.i18n.I18n._; +import static org.nuiton.i18n.I18n.n_; + +/** + * Service to export batches from a satellite post into a master post. + * + * @author kmorin <kmorin@codelutin.com> + * @author tchemit <chemit@codelutin.com> + * @since 2.2 + */ +public class MultiPostExportService extends AbstractTuttiService { + +// private static final Log log = +// LogFactory.getLog(TuttiMultiPostImportExportService.class); + + public static final String BATCHES_KEY = "batchesKey"; + + protected static final String ATTACHMENTS_DIRECTORY = "attachments"; + + protected static final String ATTACHMENTS_FILE = "attachments.csv"; + + protected static final String SPECIES_FILE = "species.csv"; + + protected static final String BENTHOS_FILE = "benthos.csv"; + + protected static final String MARINE_LITTER_FILE = "marineLitter.csv"; + + protected static final String INDIVIDUAL_OBSERVATION_FILE = "individualObservation.csv"; + + protected static final String ACCIDENTAL_CATCHES_FILE = "accidentalCatches.csv"; + + protected static final String FREQUENCIES_FILE = "frequencies.csv"; + + protected static final String CARACTERISTIC_FILE = "caracteristics.csv"; + + protected static final String WEIGHTS_FILE = "weights.csv"; + + protected PersistenceService persistenceService; + + protected DecoratorService decoratorService; + + protected char csvSeparator; + + protected SampleCategoryModel sampleCategoryModel; + + protected Map<String, CaracteristicQualitativeValue> sampleCategoryValueMap; + + @Override + public void setServiceContext(TuttiServiceContext context) { + super.setServiceContext(context); + persistenceService = getService(PersistenceService.class); + decoratorService = getService(DecoratorService.class); + + csvSeparator = context.getConfig().getCsvSeparator(); + + sampleCategoryModel = context.getSampleCategoryModel(); + + sampleCategoryValueMap = Maps.newTreeMap(); + + for (SampleCategoryModelEntry sampleCategoryModelEntry : sampleCategoryModel.getCategory()) { + Caracteristic caracteristic = sampleCategoryModelEntry.getCaracteristic(); + if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { + List<CaracteristicQualitativeValue> qualitativeValue = caracteristic.getQualitativeValue(); + for (CaracteristicQualitativeValue value : qualitativeValue) { + sampleCategoryValueMap.put(value.getId(), value); + } + } + } + } + + /** + * Export species batches. + * + * @param file the file to export the batches into + * @param operation the operation to export + */ + public void exportSpecies(File file, FishingOperation operation) { + + String operationId = operation.getId(); + if (persistenceService.isFishingOperationWithCatchBatch(operationId)) { + + // create rows + + BatchContainer<SpeciesBatch> speciesBatchContainer = + persistenceService.getRootSpeciesBatch(operationId, null); + + List<CatchRow> rows = Lists.newArrayList(); + List<CatchFrequencyRow> frequencyRows = Lists.newArrayList(); + List<AttachmentRow> attachmentRows = Lists.newArrayList(); + + for (SpeciesBatch batch : speciesBatchContainer.getChildren()) { + createSpeciesRow(batch, null, rows, frequencyRows, attachmentRows); + } + + // export catches + weights + attachments + + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operationId); + CatchWeightsRow weights = new CatchWeightsRow(); + weights.setTotalSortedWeight(catchBatch.getSpeciesTotalSortedWeight()); + weights.setInertWeight(catchBatch.getSpeciesTotalInertWeight()); + weights.setLivingNotItemizedWeight(catchBatch.getSpeciesTotalLivingNotItemizedWeight()); + exportOperation(weights, operation); + + exportCatches(file, + SPECIES_FILE, + weights, + rows, + frequencyRows, + attachmentRows); + } + } + + /** + * Export benthos batches. + * + * @param file the file to export the batches into + * @param operation the operation to export + */ + public void exportBenthos(File file, FishingOperation operation) { + + String operationId = operation.getId(); + if (persistenceService.isFishingOperationWithCatchBatch(operationId)) { + + BatchContainer<BenthosBatch> benthosBatchContainer = + persistenceService.getRootBenthosBatch(operationId, null); + + // create rows + + List<CatchRow> rows = Lists.newArrayList(); + List<CatchFrequencyRow> frequencyRows = Lists.newArrayList(); + List<AttachmentRow> attachmentRows = Lists.newArrayList(); + + for (BenthosBatch batch : benthosBatchContainer.getChildren()) { + createBenthosRow(batch, null, rows, frequencyRows, attachmentRows); + } + + // export catches + weights + attachments + + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operationId); + CatchWeightsRow weights = new CatchWeightsRow(); + weights.setTotalSortedWeight(catchBatch.getBenthosTotalSortedWeight()); + weights.setInertWeight(catchBatch.getBenthosTotalInertWeight()); + weights.setLivingNotItemizedWeight(catchBatch.getBenthosTotalLivingNotItemizedWeight()); + exportOperation(weights, operation); + + exportCatches(file, + BENTHOS_FILE, + weights, + rows, + frequencyRows, + attachmentRows); + } + } + + /** + * Export marine litter batches. + * + * @param file the file to export the batches into + * @param operation the operation to export + */ + public void exportMarineLitter(File file, FishingOperation operation) { + + String operationId = operation.getId(); + if (persistenceService.isFishingOperationWithCatchBatch(operationId)) { + + // create rows + + BatchContainer<MarineLitterBatch> marineLitterBatchContainer = + persistenceService.getRootMarineLitterBatch(operationId); + + List<MarineLitterRow> rows = Lists.newArrayList(); + List<AttachmentRow> attachmentRows = Lists.newArrayList(); + + for (MarineLitterBatch batch : marineLitterBatchContainer.getChildren()) { + MarineLitterRow row = new MarineLitterRow(); + + String id = context.generateId(MarineLitterRow.class); + row.setBatchId(id); + + row.setCategory(batch.getMarineLitterCategory()); + row.setSizeCategory(batch.getMarineLitterSizeCategory()); + row.setNumber(batch.getNumber()); + row.setWeight(batch.getWeight()); + row.setComment(batch.getComment()); + + rows.add(row); + + addAttachments(id, + batch.getIdAsInt(), + AttachementObjectTypeEnum.BATCH, + attachmentRows); + } + + + File directory = Files.createTempDir(); + List<File> file2zip = Lists.newArrayList(); + + // export marine litters + + MarineLitterRowModel marineLitterRowModel = new MarineLitterRowModel(csvSeparator); + File marineLitterFile = new File(directory, MARINE_LITTER_FILE); + file2zip.add(marineLitterFile); + export(marineLitterFile, + marineLitterRowModel, + rows, + n_("tutti.service.multipost.export.batches.error")); + + // export weights + + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operationId); + MarineLitterWeightRow weight = new MarineLitterWeightRow(); + weight.setTotalWeight(catchBatch.getMarineLitterTotalWeight()); + exportOperation(weight, operation); + + MarineLitterWeightRowModel weightModel = new MarineLitterWeightRowModel(csvSeparator); + + File weightFile = new File(directory, WEIGHTS_FILE); + file2zip.add(weightFile); + export(weightFile, + weightModel, + Lists.newArrayList(weight), + n_("tutti.service.multipost.export.weight.error")); + + // export attachments + create final zip + + exportAttachmentsAndCreateZip(file, + directory, + file2zip, + attachmentRows); + } + } + + /** + * Export individual observation batches. + * + * @param file the file to export the batches into + * @param operation the operation to export + */ + public void exportIndividualObservation(File file, FishingOperation operation) { + List<IndividualObservationBatch> individualObservations = + persistenceService.getAllIndividualObservationBatch(operation.getId()); + + // create rows + + List<IndividualObservationRow> rows = Lists.newArrayList(); + List<CaracteristicRow> caracteristicRows = Lists.newArrayList(); + List<AttachmentRow> attachmentRows = Lists.newArrayList(); + + + for (IndividualObservationBatch batch : individualObservations) { + IndividualObservationRow row = new IndividualObservationRow(); + + String id = context.generateId(IndividualObservationRow.class); + row.setBatchId(id); + + row.setSpecies(batch.getSpecies()); + row.setWeight(batch.getWeight()); + row.setSize(batch.getSize()); + row.setLengthStepCaracteristic(batch.getLengthStepCaracteristic()); +// row.setSamplingCode(batch.getSamplingCode()); +// row.setCalcifiedPieceSamplingCode(batch.getCalcifiedPieceSamplingCode()); + row.setComment(batch.getComment()); + + rows.add(row); + + CaracteristicMap caracteristicMap = batch.getCaracteristics(); + for (Caracteristic caracteristic : caracteristicMap.keySet()) { + CaracteristicRow caracteristicRow = new CaracteristicRow(); + caracteristicRow.setBatchId(id); + caracteristicRow.setCaracteristic(caracteristic); + caracteristicRow.setValue(caracteristicMap.get(caracteristic)); + caracteristicRows.add(caracteristicRow); + } + + addAttachments(id, batch.getIdAsInt(), AttachementObjectTypeEnum.SAMPLE, attachmentRows); + } + + File directory = Files.createTempDir(); + List<File> file2zip = Lists.newArrayList(); + + // export individual observations + + IndividualObservationRowModel csvModel = new IndividualObservationRowModel(csvSeparator); + File individualObservationFile = new File(directory, INDIVIDUAL_OBSERVATION_FILE); + file2zip.add(individualObservationFile); + export(individualObservationFile, + csvModel, + rows, + n_("tutti.service.multipost.export.batches.error")); + + // export caracteristics + + CaracteristicRowModel caracteristicCsvModel = new CaracteristicRowModel(csvSeparator); + File caracteristicFile = new File(directory, CARACTERISTIC_FILE); + file2zip.add(caracteristicFile); + export(caracteristicFile, + caracteristicCsvModel, + caracteristicRows, + n_("tutti.service.multipost.export.batches.error")); + + // export operation + + FishingOperationRow foRow = new FishingOperationRow(); + exportOperation(foRow, operation); + + FishingOperationRowModel foRowModel = new FishingOperationRowModel(csvSeparator); + + File weightFile = new File(directory, WEIGHTS_FILE); + file2zip.add(weightFile); + export(weightFile, + foRowModel, + Lists.newArrayList(foRow), + n_("tutti.service.multipost.export.operation.error")); + + // export attachments + create final zip + + exportAttachmentsAndCreateZip(file, + directory, + file2zip, + attachmentRows); + } + + /** + * Export accidental catch batches. + * + * @param file the file to export the batches into + * @param operation the operation to export + */ + public void exportAccidentalCatch(File file, FishingOperation operation) { + List<AccidentalBatch> accidentalCatches = + persistenceService.getAllAccidentalBatch(operation.getId()); + + List<AccidentalCatchRow> rows = Lists.newArrayList(); + List<CaracteristicRow> caracteristicRows = Lists.newArrayList(); + List<AttachmentRow> attachmentRows = Lists.newArrayList(); + + // create rows + + for (AccidentalBatch batch : accidentalCatches) { + AccidentalCatchRow row = new AccidentalCatchRow(); + + String id = context.generateId(AccidentalCatchRow.class); + row.setBatchId(id); + + row.setSpecies(batch.getSpecies()); + row.setGender(batch.getGender()); + row.setWeight(batch.getWeight()); + row.setSize(batch.getSize()); + row.setLengthStepCaracteristic(batch.getLengthStepCaracteristic()); + row.setDeadOrAlive(batch.getDeadOrAlive()); + row.setComment(batch.getComment()); + + rows.add(row); + + CaracteristicMap caracteristicMap = batch.getCaracteristics(); + for (Caracteristic caracteristic : caracteristicMap.keySet()) { + CaracteristicRow caracteristicRow = new CaracteristicRow(); + caracteristicRow.setBatchId(id); + caracteristicRow.setCaracteristic(caracteristic); + caracteristicRow.setValue(caracteristicMap.get(caracteristic)); + caracteristicRows.add(caracteristicRow); + } + + addAttachments(id, batch.getIdAsInt(), AttachementObjectTypeEnum.SAMPLE, attachmentRows); + } + + // export accidental catches + + AccidentalCatchRowModel csvModel = new AccidentalCatchRowModel(csvSeparator); + + File directory = Files.createTempDir(); + List<File> file2zip = Lists.newArrayList(); + + File accidentalCatchesFile = new File(directory, ACCIDENTAL_CATCHES_FILE); + file2zip.add(accidentalCatchesFile); + export(accidentalCatchesFile, + csvModel, + rows, + n_("tutti.service.multipost.export.batches.error")); + + // export caracteristics + + CaracteristicRowModel caracteristicCsvModel = new CaracteristicRowModel(csvSeparator); + File caracteristicFile = new File(directory, CARACTERISTIC_FILE); + file2zip.add(caracteristicFile); + export(caracteristicFile, + caracteristicCsvModel, + caracteristicRows, + n_("tutti.service.multipost.export.batches.error")); + + // export operation + + FishingOperationRow foRow = new FishingOperationRow(); + exportOperation(foRow, operation); + + FishingOperationRowModel foRowModel = new FishingOperationRowModel(csvSeparator); + + File weightFile = new File(directory, WEIGHTS_FILE); + file2zip.add(weightFile); + export(weightFile, + foRowModel, + Lists.newArrayList(foRow), + n_("tutti.service.multipost.export.operation.error")); + + // export attachments + create final zip + + exportAttachmentsAndCreateZip(file, + directory, + file2zip, + attachmentRows); + } + + //------------------------------------------------------------------------// + //-- Internal methods --// + //------------------------------------------------------------------------// + + protected void exportCatches(File file, + String batchFile, + CatchWeightsRow weights, + List<CatchRow> rows, + List<CatchFrequencyRow> frequencyRows, + List<AttachmentRow> attachmentRows) { + CatchRowModel csvModel = new CatchRowModel(csvSeparator); + CatchFrequencyRowModel csvFrequencyModel = new CatchFrequencyRowModel(csvSeparator); + CatchWeightsRowModel catchWeightsModel = new CatchWeightsRowModel(csvSeparator); + + File directory = Files.createTempDir(); + List<File> file2zip = Lists.newArrayList(); + + File weightsFile = new File(directory, WEIGHTS_FILE); + file2zip.add(weightsFile); + export(weightsFile, + catchWeightsModel, + Lists.newArrayList(weights), + n_("tutti.service.multipost.export.weights.error")); + + File speciesFile = new File(directory, batchFile); + file2zip.add(speciesFile); + export(speciesFile, + csvModel, + rows, + n_("tutti.service.multipost.export.batches.error")); + + File frequencyFile = new File(directory, FREQUENCIES_FILE); + file2zip.add(frequencyFile); + export(frequencyFile, + csvFrequencyModel, + frequencyRows, + n_("tutti.service.multipost.export.frequencies.error")); + + // export attachments + create final zip + + exportAttachmentsAndCreateZip(file, + directory, + file2zip, + attachmentRows); + } + + protected void createSpeciesRow(SpeciesBatch batch, + String parentId, + List<CatchRow> rows, + List<CatchFrequencyRow> frequencyRows, + List<AttachmentRow> attachmentRows) { + CatchRow row = new CatchRow(); + + String id = context.generateId(CatchRow.class); + row.setId(id); + row.setParentId(parentId); + row.setSpecies(batch.getSpecies()); + + row.setCategoryId(batch.getSampleCategoryId()); + row.setCategoryValue(batch.getSampleCategoryValue()); + row.setCategoryWeight(batch.getSampleCategoryWeight()); + row.setWeight(batch.getWeight()); + row.setNumber(batch.getNumber()); + row.setComment(batch.getComment()); + row.setToConfirm(batch.isSpeciesToConfirm()); + + rows.add(row); + + addFrequencies(id, batch.getId(), frequencyRows); + addAttachments(id, batch.getIdAsInt(), AttachementObjectTypeEnum.BATCH, attachmentRows); + + for (SpeciesBatch child : batch.getChildBatchs()) { + createSpeciesRow(child, id, rows, frequencyRows, attachmentRows); + } + } + + protected void createBenthosRow(BenthosBatch batch, + String parentId, + List<CatchRow> rows, + List<CatchFrequencyRow> frequencyRows, + List<AttachmentRow> attachmentRows) { + CatchRow row = new CatchRow(); + + String id = context.generateId(CatchRow.class); + row.setId(id); + row.setParentId(parentId); + row.setSpecies(batch.getSpecies()); + + row.setCategoryId(batch.getSampleCategoryId()); + row.setCategoryValue(batch.getSampleCategoryValue()); + row.setCategoryWeight(batch.getSampleCategoryWeight()); + row.setWeight(batch.getWeight()); + row.setNumber(batch.getNumber()); + row.setComment(batch.getComment()); + row.setToConfirm(batch.isSpeciesToConfirm()); + + rows.add(row); + + addFrequencies(id, batch.getId(), frequencyRows); + addAttachments(id, batch.getIdAsInt(), AttachementObjectTypeEnum.BATCH, attachmentRows); + + for (BenthosBatch child : batch.getChildBatchs()) { + createBenthosRow(child, id, rows, frequencyRows, attachmentRows); + } + } + + protected void exportOperation(AbstractFishingOperationRow afoRow, FishingOperation operation) { + afoRow.setStationNumber(operation.getStationNumber()); + afoRow.setOperationNumber(operation.getFishingOperationNumber()); + afoRow.setMultirigAggregation(operation.getMultirigAggregation()); + afoRow.setDate(operation.getGearShootingStartDate()); + } + + protected void addFrequencies(String rowId, + String batchId, + List<CatchFrequencyRow> frequencyRows) { + List<SpeciesBatchFrequency> frequencies = + persistenceService.getAllSpeciesBatchFrequency(batchId); + for (SpeciesBatchFrequency frequency : frequencies) { + CatchFrequencyRow frequencyRow = new CatchFrequencyRow(); + frequencyRow.setBatchId(rowId); + frequencyRow.setLengthStepCaracteristic(frequency.getLengthStepCaracteristic()); + frequencyRow.setLengthStep(frequency.getLengthStep()); + frequencyRow.setNumber(frequency.getNumber()); + frequencyRow.setWeight(frequency.getWeight()); + frequencyRows.add(frequencyRow); + } + } + + protected void addAttachments(String batchId, + int objectId, + AttachementObjectTypeEnum objectType, + List<AttachmentRow> attachmentRows) { + List<Attachment> attachments = + persistenceService.getAllAttachments(objectType, objectId); + for (Attachment attachment : attachments) { + AttachmentRow attachmentRow = new AttachmentRow(); + attachmentRow.setBatchId(batchId); + attachmentRow.setName(attachment.getName()); + attachmentRow.setComment(attachment.getComment()); + attachmentRow.setFile(persistenceService.getAttachmentFile(attachment.getId())); + attachmentRows.add(attachmentRow); + } + } + + + protected <R> void export(File file, + ExportModel<R> exportModel, + List<R> rows, + String errorMessage) { + Writer writer = TuttiIOUtil.newWriter( + file, + n_("tutti.service.multipost.export.file.writer.error")); + try { + Export export = Export.newExport(exportModel, rows); + export.write(writer); + writer.close(); + + } catch (Exception e) { + throw new TuttiTechnicalException(_(errorMessage, file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + protected void exportAttachments(File directory, + List<File> file2zip, + List<AttachmentRow> attachmentRows) { + + AttachmentRowModel csvAttachmentModel = new AttachmentRowModel(csvSeparator); + + File attachmentDirectory = new File(directory, ATTACHMENTS_DIRECTORY); + TuttiIOUtil.forceMkdir(attachmentDirectory, _("tutti.service.multipost.attachment.mkdir.error", attachmentDirectory)); + file2zip.add(attachmentDirectory); + for (AttachmentRow attachmentRow : attachmentRows) { + File attachmentFile = attachmentRow.getFile(); + File destFile = new File(attachmentDirectory, attachmentFile.getName()); + TuttiIOUtil.copyFile(attachmentFile, + destFile, + _("tutti.service.multipost.attachment.copy.error", attachmentFile)); + file2zip.add(destFile); + } + + File attachmentFile = new File(directory, ATTACHMENTS_FILE); + file2zip.add(attachmentFile); + export(attachmentFile, + csvAttachmentModel, + attachmentRows, + n_("tutti.service.multipost.export.attachments.error")); + + } + + protected void exportAttachmentsAndCreateZip(File file, + File directory, + List<File> file2zip, + List<AttachmentRow> attachmentRows) { + exportAttachments(directory, file2zip, attachmentRows); + + try { + TuttiIOUtil.zip(directory, + file, + file2zip, + n_("tutti.service.multipost.export.error")); + } finally { + TuttiIOUtil.deleteDirectory(directory, _("tutti.service.multipost.export.deleteTempDirectory.error", file)); + } + } +} Copied: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/MultiPostImportService.java (from rev 1246, trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostImportService.java) =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/MultiPostImportService.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/MultiPostImportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,1321 @@ +package fr.ifremer.tutti.service.catches.multipost; + +/* + * #%L + * Tutti :: Service + * $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.Function; +import com.google.common.base.Preconditions; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ListMultimap; +import com.google.common.collect.Maps; +import fr.ifremer.tutti.TuttiBusinessException; +import fr.ifremer.tutti.TuttiIOUtil; +import fr.ifremer.tutti.persistence.entities.CaracteristicMap; +import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; +import fr.ifremer.tutti.persistence.entities.TuttiEntities; +import fr.ifremer.tutti.persistence.entities.TuttiEntity; +import fr.ifremer.tutti.persistence.entities.data.AccidentalBatch; +import fr.ifremer.tutti.persistence.entities.data.AttachementObjectTypeEnum; +import fr.ifremer.tutti.persistence.entities.data.Attachment; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatchFrequency; +import fr.ifremer.tutti.persistence.entities.data.CatchBatch; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.IndividualObservationBatch; +import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; +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.service.AbstractTuttiService; +import fr.ifremer.tutti.service.DecoratorService; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.TuttiDataContext; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.nuiton.csv.Import; + +import java.io.File; +import java.io.Reader; +import java.io.Serializable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +import static org.nuiton.i18n.I18n._; +import static org.nuiton.i18n.I18n.n_; + +/** + * Service to export batches from a satellite post or import batches + * into a master post. + * + * @author kmorin <kmorin@codelutin.com> + * @since 2.2 + */ +public class MultiPostImportService extends AbstractTuttiService { + +// private static final Log log = +// LogFactory.getLog(TuttiMultiPostImportExportService.class); + + public static final String BATCHES_KEY = "batchesKey"; + + protected static final String ATTACHMENTS_DIRECTORY = "attachments"; + + protected static final String ATTACHMENTS_FILE = "attachments.csv"; + + protected static final String SPECIES_FILE = "species.csv"; + + protected static final String BENTHOS_FILE = "benthos.csv"; + + protected static final String MARINE_LITTER_FILE = "marineLitter.csv"; + + protected static final String INDIVIDUAL_OBSERVATION_FILE = "individualObservation.csv"; + + protected static final String ACCIDENTAL_CATCHES_FILE = "accidentalCatches.csv"; + + protected static final String FREQUENCIES_FILE = "frequencies.csv"; + + protected static final String CARACTERISTIC_FILE = "caracteristics.csv"; + + protected static final String WEIGHTS_FILE = "weights.csv"; + + protected PersistenceService persistenceService; + + protected DecoratorService decoratorService; + + protected char csvSeparator; + + protected SampleCategoryModel sampleCategoryModel; + + protected Map<String, CaracteristicQualitativeValue> sampleCategoryValueMap; + + @Override + public void setServiceContext(TuttiServiceContext context) { + super.setServiceContext(context); + persistenceService = getService(PersistenceService.class); + decoratorService = getService(DecoratorService.class); + + csvSeparator = context.getConfig().getCsvSeparator(); + + sampleCategoryModel = context.getSampleCategoryModel(); + + sampleCategoryValueMap = Maps.newTreeMap(); + + for (SampleCategoryModelEntry sampleCategoryModelEntry : sampleCategoryModel.getCategory()) { + Caracteristic caracteristic = sampleCategoryModelEntry.getCaracteristic(); + if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { + List<CaracteristicQualitativeValue> qualitativeValue = caracteristic.getQualitativeValue(); + for (CaracteristicQualitativeValue value : qualitativeValue) { + sampleCategoryValueMap.put(value.getId(), value); + } + } + } + } + + //------------------------------------------------------------------------// + //-- Import Species --// + //------------------------------------------------------------------------// + + /** + * Import species batches from a satellite post + * + * @param file the file to import the batches from + * @param operation the operation in which to add the batches + * @return the list of the species which have not been imported, because there were concurrent batches + */ + public Map<String, Object> importSpecies(final File file, + final FishingOperation operation) { + + Callable<Map<String, Object>> call = new Callable<Map<String, Object>>() { + + @Override + public Map<String, Object> call() throws Exception { + + File tempDir = TuttiIOUtil.explodeZip( + context.getConfig().getTmpDirectory(), + file, + n_("tutti.service.multipost.uncompress.error")); + + //check operation + CatchWeightsRowModel weightsModel = new CatchWeightsRowModel(csvSeparator); + checkSameOperation(tempDir, weightsModel, operation); + + final Map<String, Object> notImportedData = Maps.newHashMap(); + + final Map<String, SpeciesBatch> notImportedBatches = Maps.newLinkedHashMap(); + + BatchContainer<SpeciesBatch> speciesBatches = + persistenceService.getRootSpeciesBatch(operation.getId(), null); + + TuttiDataContext dataContext = context.getDataContext(); + List<Species> speciesList = dataContext.getReferentSpecies(); + + // Import batches + // map containing the batches by their persistence id + + final Map<String, SpeciesBatch> batches = importSpeciesBatches( + tempDir, + operation, + speciesBatches, + notImportedBatches, + speciesList); + + List<Caracteristic> caracteristics = dataContext.getCaracteristics(); + + // Import frequencies + + importSpeciesFrequencies( + tempDir, + batches, + notImportedBatches, + caracteristics); + + // Import attachments + + importAttachments(tempDir, + batches, + notImportedBatches, + AttachementObjectTypeEnum.BATCH); + + // Import weights + + importSpeciesWeights(tempDir, + operation, + weightsModel, + notImportedData); + + notImportedData.put(BATCHES_KEY, notImportedBatches.values()); + + return notImportedData; + } + }; + + Map<String, Object> result = persistenceService.invoke(call); + return result; + } + + protected Map<String, SpeciesBatch> importSpeciesBatches(File file, + FishingOperation operation, + BatchContainer<SpeciesBatch> speciesBatches, + Map<String, SpeciesBatch> notImportedBatches, + List<Species> speciesList) { + final Map<String, SpeciesBatch> batches = Maps.newHashMap(); + + Reader reader = TuttiIOUtil.newReader( + new File(file, SPECIES_FILE), + n_("tutti.service.multipost.import.batches.error")); + + try { + CatchRowModel csvModel = new CatchRowModel(csvSeparator, + speciesList); + + Import<CatchRow> importer = Import.newImport(csvModel, reader); + + try { + for (CatchRow row : importer) { + + // create batch + SpeciesBatch batch = TuttiBeanFactory.newSpeciesBatch(); + batch.setFishingOperation(operation); + + Species species = row.getSpecies(); + batch.setSpecies(row.getSpecies()); + batch.setWeight(row.getWeight()); + batch.setNumber(row.getNumber()); + batch.setComment(row.getComment()); + batch.setSpeciesToConfirm(row.isToConfirm()); + + Pair<Integer, Serializable> valueAndCategoryType = getValueAndCategoryType(row); + Integer categoryId = valueAndCategoryType.getKey(); + Serializable value = valueAndCategoryType.getValue(); + + batch.setSampleCategoryId(categoryId); + batch.setSampleCategoryValue(value); + batch.setSampleCategoryWeight(row.getCategoryWeight()); + + // get parent batch + String parentId = row.getParentId(); + String parentPersistedId = null; + SpeciesBatch parent = null; + if (StringUtils.isNotEmpty(parentId)) { + parent = batches.get(parentId); + parentPersistedId = parent.getId(); + } + + SpeciesBatch existingBatch = null; + List<SpeciesBatch> batchesToBrowse; + if (parent == null) { + batchesToBrowse = speciesBatches.getChildren(); + } else { + batchesToBrowse = parent.getChildBatchs(); + } + + // check if the parent has already a batch with the caracteristic value + // and if the children batch are categorized with the same caracterstic + if (batchesToBrowse != null) { + for (SpeciesBatch sb : batchesToBrowse) { + if (sb.getSpecies().equals(species) + && (!sb.getSampleCategoryId().equals(batch.getSampleCategoryId()) + || sb.getSampleCategoryValue().equals(value))) { + + existingBatch = sb; + batches.put(row.getId(), sb); + notImportedBatches.put(row.getId(), batch); + break; + } + } + } + + if (existingBatch == null) { + batch = persistenceService.createSpeciesBatch(batch, parentPersistedId); + batches.put(row.getId(), batch); + } + } + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + return batches; + } + + protected void importSpeciesFrequencies( + File file, + Map<String, SpeciesBatch> batches, + Map<String, SpeciesBatch> notImportedBatches, + List<Caracteristic> caracteristics) { + ListMultimap<String, SpeciesBatchFrequency> frequencyMap = + ArrayListMultimap.create(); + + Reader reader = TuttiIOUtil.newReader( + new File(file, FREQUENCIES_FILE), + n_("tutti.service.multipost.import.frequencies.error")); + + try { + + CatchFrequencyRowModel frequencyModel = new CatchFrequencyRowModel(csvSeparator, + caracteristics); + + Import<CatchFrequencyRow> importer = Import.newImport(frequencyModel, reader); + + try { + for (CatchFrequencyRow frequencyRow : importer) { + if (notImportedBatches.get(frequencyRow.getBatchId()) == null) { + SpeciesBatch batch = batches.get(frequencyRow.getBatchId()); + if (batch != null) { + SpeciesBatchFrequency frequency = TuttiBeanFactory.newSpeciesBatchFrequency(); + frequency.setLengthStepCaracteristic(frequencyRow.getLengthStepCaracteristic()); + frequency.setLengthStep(frequencyRow.getLengthStep()); + frequency.setNumber(frequencyRow.getNumber()); + frequency.setWeight(frequencyRow.getWeight()); + frequency.setBatch(batch); + frequencyMap.put(batch.getId(), frequency); + } + } + } + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + + for (String batchId : frequencyMap.keySet()) { + List<SpeciesBatchFrequency> frequencies = frequencyMap.get(batchId); + persistenceService.saveSpeciesBatchFrequency(batchId, frequencies); + } + } + + protected void importSpeciesWeights(File file, + FishingOperation operation, + CatchWeightsRowModel weightsModel, + Map<String, Object> notImportedData) { + Reader reader = TuttiIOUtil.newReader( + new File(file, WEIGHTS_FILE), + n_("tutti.service.multipost.import.weights.error")); + + try { + Import<CatchWeightsRow> importer = Import.newImport(weightsModel, reader); + + try { + Iterator<CatchWeightsRow> iterator = importer.iterator(); + if (iterator.hasNext()) { + CatchWeightsRow row = iterator.next(); + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operation.getId()); + catchBatch.setFishingOperation(operation); + + if (catchBatch.getSpeciesTotalSortedWeight() == null) { + catchBatch.setSpeciesTotalSortedWeight(row.getTotalSortedWeight()); + + } else if (row.getTotalSortedWeight() != null) { + notImportedData.put(CatchBatch.PROPERTY_SPECIES_TOTAL_SORTED_WEIGHT, row.getTotalSortedWeight()); + } + + if (catchBatch.getSpeciesTotalInertWeight() == null) { + catchBatch.setSpeciesTotalInertWeight(row.getInertWeight()); + + } else if (row.getInertWeight() != null) { + notImportedData.put(CatchBatch.PROPERTY_SPECIES_TOTAL_INERT_WEIGHT, row.getInertWeight()); + } + + if (catchBatch.getSpeciesTotalLivingNotItemizedWeight() == null) { + catchBatch.setSpeciesTotalLivingNotItemizedWeight(row.getLivingNotItemizedWeight()); + + } else if (row.getLivingNotItemizedWeight() != null) { + notImportedData.put(CatchBatch.PROPERTY_SPECIES_TOTAL_LIVING_NOT_ITEMIZED_WEIGHT, + row.getLivingNotItemizedWeight()); + } + persistenceService.saveCatchBatch(catchBatch); + } + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + } + + //------------------------------------------------------------------------// + //-- Import Benthos --// + //------------------------------------------------------------------------// + + /** + * Import benthos batches from a satellite post + * + * @param file the file to import the batches from + * @param operation the operation in which to add the batches + * @return the list of the benthos which have not been imported, because there were concurrent batches + */ + public Map<String, Object> importBenthos(final File file, + final FishingOperation operation) { + + Callable<Map<String, Object>> call = new Callable<Map<String, Object>>() { + + @Override + public Map<String, Object> call() throws Exception { + + File tempDir = TuttiIOUtil.explodeZip( + context.getConfig().getTmpDirectory(), + file, + n_("tutti.service.multipost.uncompress.error")); + + //check operation + CatchWeightsRowModel weightsModel = new CatchWeightsRowModel(csvSeparator); + checkSameOperation(tempDir, weightsModel, operation); + + Map<String, Object> notImportedData = Maps.newHashMap(); + final Map<String, BenthosBatch> notImportedBatches = Maps.newLinkedHashMap(); + + BatchContainer<BenthosBatch> benthosBatches = + persistenceService.getRootBenthosBatch(operation.getId(), null); + + TuttiDataContext dataContext = context.getDataContext(); + List<Species> speciesList = dataContext.getReferentSpecies(); + + // Import batches + // map containing the batches by their persistence id + final Map<String, BenthosBatch> batches = importBenthosBatches( + tempDir, + operation, + benthosBatches, + notImportedBatches, + speciesList); + + // Import frequencies + + importBenthosFrequencies( + tempDir, + batches, + notImportedBatches, + dataContext.getCaracteristics()); + + // Import attachments + + importAttachments(tempDir, + batches, + notImportedBatches, + AttachementObjectTypeEnum.BATCH); + + // Import weights + + importBenthosWeights(tempDir, + operation, + weightsModel, + notImportedData); + + notImportedData.put(BATCHES_KEY, notImportedBatches.values()); + return notImportedData; + } + }; + + Map<String, Object> result = persistenceService.invoke(call); + return result; + } + + protected Map<String, BenthosBatch> importBenthosBatches(File file, + FishingOperation operation, + BatchContainer<BenthosBatch> benthosBatches, + Map<String, BenthosBatch> notImportedBatches, + List<Species> speciesList) { + final Map<String, BenthosBatch> batches = Maps.newHashMap(); + Reader reader = TuttiIOUtil.newReader( + new File(file, BENTHOS_FILE), + n_("tutti.service.multipost.import.batches.error")); + + try { + CatchRowModel csvModel = new CatchRowModel(csvSeparator, + speciesList); + + Import<CatchRow> importer = Import.newImport(csvModel, reader); + + try { + for (CatchRow row : importer) { + + // create batch + BenthosBatch batch = TuttiBeanFactory.newBenthosBatch(); + batch.setFishingOperation(operation); + + Species species = row.getSpecies(); + batch.setSpecies(row.getSpecies()); + batch.setWeight(row.getWeight()); + batch.setNumber(row.getNumber()); + batch.setComment(row.getComment()); + batch.setSpeciesToConfirm(row.isToConfirm()); + + Pair<Integer, Serializable> valueAndCategoryType = getValueAndCategoryType(row); + Integer categoryId = valueAndCategoryType.getKey(); + Serializable value = valueAndCategoryType.getValue(); + + batch.setSampleCategoryId(categoryId); + batch.setSampleCategoryValue(value); + batch.setSampleCategoryWeight(row.getCategoryWeight()); + + // get parent batch + String parentId = row.getParentId(); + String parentPersistedId = null; + BenthosBatch parent = null; + if (StringUtils.isNotEmpty(parentId)) { + parent = batches.get(parentId); + parentPersistedId = parent.getId(); + } + + BenthosBatch existingBatch = null; + List<BenthosBatch> batchesToBrowse; + if (parent == null) { + batchesToBrowse = benthosBatches.getChildren(); + } else { + batchesToBrowse = parent.getChildBatchs(); + } + + // check if the parent has already a batch with the caracteristic value + // and if the children batch are categorized with the same caracterstic + if (batchesToBrowse != null) { + for (BenthosBatch bb : batchesToBrowse) { + if (bb.getSpecies().equals(species) + && (!bb.getSampleCategoryId().equals(batch.getSampleCategoryId()) + || bb.getSampleCategoryValue().equals(value))) { + + existingBatch = bb; + batches.put(row.getId(), bb); + notImportedBatches.put(row.getId(), batch); + break; + } + } + } + + if (existingBatch == null) { + batch = persistenceService.createBenthosBatch(batch, parentPersistedId); + batches.put(row.getId(), batch); + } + } + + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + return batches; + } + + protected void importBenthosFrequencies(File file, + Map<String, BenthosBatch> batches, + Map<String, BenthosBatch> notImportedBatches, + List<Caracteristic> caracteristics) { + ListMultimap<String, BenthosBatchFrequency> frequencyMap = + ArrayListMultimap.create(); + + Reader reader = TuttiIOUtil.newReader( + new File(file, FREQUENCIES_FILE), + n_("tutti.service.multipost.import.frequencies.error")); + try { + CatchFrequencyRowModel frequencyModel = new CatchFrequencyRowModel(csvSeparator, + caracteristics); + + Import<CatchFrequencyRow> importer = Import.newImport(frequencyModel, reader); + + try { + + for (CatchFrequencyRow frequencyRow : importer) { + if (notImportedBatches.get(frequencyRow.getBatchId()) == null) { + BenthosBatch batch = batches.get(frequencyRow.getBatchId()); + if (batch != null) { + BenthosBatchFrequency frequency = TuttiBeanFactory.newBenthosBatchFrequency(); + frequency.setLengthStepCaracteristic(frequencyRow.getLengthStepCaracteristic()); + frequency.setLengthStep(frequencyRow.getLengthStep()); + frequency.setNumber(frequencyRow.getNumber()); + frequency.setWeight(frequencyRow.getWeight()); + frequency.setBatch(batch); + frequencyMap.put(batch.getId(), frequency); + } + } + } + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + + for (String batchId : frequencyMap.keySet()) { + List<BenthosBatchFrequency> frequencies = frequencyMap.get(batchId); + persistenceService.saveBenthosBatchFrequency(batchId, frequencies); + } + } + + protected void importBenthosWeights(File file, + FishingOperation operation, + CatchWeightsRowModel weightsModel, + Map<String, Object> notImportedData) { + Reader reader = TuttiIOUtil.newReader( + new File(file, WEIGHTS_FILE), + n_("tutti.service.multipost.import.weights.error")); + + try { + Import<CatchWeightsRow> importer = Import.newImport(weightsModel, reader); + + try { + Iterator<CatchWeightsRow> iterator = importer.iterator(); + if (iterator.hasNext()) { + CatchWeightsRow row = iterator.next(); + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operation.getId()); + catchBatch.setFishingOperation(operation); + + if (catchBatch.getBenthosTotalSortedWeight() == null) { + catchBatch.setBenthosTotalSortedWeight(row.getTotalSortedWeight()); + + } else if (row.getTotalSortedWeight() != null) { + notImportedData.put(CatchBatch.PROPERTY_BENTHOS_TOTAL_SORTED_WEIGHT, row.getTotalSortedWeight()); + } + + if (catchBatch.getBenthosTotalInertWeight() == null) { + catchBatch.setBenthosTotalInertWeight(row.getInertWeight()); + + } else if (row.getInertWeight() != null) { + notImportedData.put(CatchBatch.PROPERTY_BENTHOS_TOTAL_INERT_WEIGHT, row.getInertWeight()); + } + + if (catchBatch.getBenthosTotalLivingNotItemizedWeight() == null) { + catchBatch.setBenthosTotalLivingNotItemizedWeight(row.getLivingNotItemizedWeight()); + + } else if (row.getLivingNotItemizedWeight() != null) { + notImportedData.put(CatchBatch.PROPERTY_BENTHOS_TOTAL_LIVING_NOT_ITEMIZED_WEIGHT, + row.getLivingNotItemizedWeight()); + } + + persistenceService.saveCatchBatch(catchBatch); + } + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + } + + //------------------------------------------------------------------------// + //-- Import Marine litter --// + //------------------------------------------------------------------------// + + /** + * Import marine litter batches from a satellite post + * + * @param file the file to import the batches from + * @param operation the operation in which to add the batches + * @return the list of the marine litter which have not been imported, because there were concurrent batches + */ + public Map<String, Object> importMarineLitter(final File file, + final FishingOperation operation) { + + Callable<Map<String, Object>> call = new Callable<Map<String, Object>>() { + + @Override + public Map<String, Object> call() throws Exception { + File tempDir = TuttiIOUtil.explodeZip( + context.getConfig().getTmpDirectory(), + file, + n_("tutti.service.multipost.uncompress.error")); + + //check operation + MarineLitterWeightRowModel weightModel = new MarineLitterWeightRowModel(csvSeparator); + checkSameOperation(tempDir, weightModel, operation); + + String operationId = operation.getId(); + + Map<String, Object> notImportedData = Maps.newHashMap(); + final Map<String, MarineLitterBatch> notImportedBatches = Maps.newLinkedHashMap(); + + BatchContainer<MarineLitterBatch> marineLitterBatches = + persistenceService.getRootMarineLitterBatch(operationId); + List<CaracteristicQualitativeValue> categoryValues = + persistenceService.getMarineLitterCategoryCaracteristic().getQualitativeValue(); + List<CaracteristicQualitativeValue> sizeCategoryValues = + persistenceService.getMarineLitterSizeCategoryCaracteristic().getQualitativeValue(); + + // Import batches + // map containing the batches by their persistence id + final Map<String, MarineLitterBatch> batches = importMarineLitterBatches( + tempDir, + operation, + categoryValues, + sizeCategoryValues, + marineLitterBatches, + notImportedBatches); + + // Import attachments + + importAttachments(tempDir, + batches, + notImportedBatches, + AttachementObjectTypeEnum.BATCH); + + // Import weights + + importMarineLitterCatchWeights(tempDir, + operation, + weightModel, + notImportedData); + + notImportedData.put(BATCHES_KEY, notImportedBatches.values()); + return notImportedData; + + } + }; + Map<String, Object> result = persistenceService.invoke(call); + return result; + } + + protected Map<String, MarineLitterBatch> importMarineLitterBatches(File file, FishingOperation operation, + List<CaracteristicQualitativeValue> categoryValues, + List<CaracteristicQualitativeValue> sizeCategoryValues, + BatchContainer<MarineLitterBatch> marineLitterBatches, + Map<String, MarineLitterBatch> notImportedBatches) { + + Map<String, MarineLitterBatch> batches = Maps.newLinkedHashMap(); + + Reader reader = TuttiIOUtil.newReader( + new File(file, MARINE_LITTER_FILE), + n_("tutti.service.multipost.import.batches.error")); + + try { + + MarineLitterRowModel csvModel = new MarineLitterRowModel(csvSeparator, + categoryValues, + sizeCategoryValues); + + Import<MarineLitterRow> importer = Import.newImport(csvModel, reader); + + try { + for (MarineLitterRow row : importer) { + + // create batch + MarineLitterBatch batch = TuttiBeanFactory.newMarineLitterBatch(); + batch.setFishingOperation(operation); + + batch.setWeight(row.getWeight()); + batch.setNumber(row.getNumber()); + batch.setComment(row.getComment()); + batch.setMarineLitterCategory(row.getCategory()); + batch.setMarineLitterSizeCategory(row.getSizeCategory()); + + MarineLitterBatch existingBatch = null; + List<MarineLitterBatch> batchesToBrowse = marineLitterBatches.getChildren(); + + // check if the parent has already a batch with the caracteristic value + // and if the children batch are categorized with the same caracterstic + if (batchesToBrowse != null) { + for (MarineLitterBatch mlb : batchesToBrowse) { + if (mlb.getMarineLitterCategory().equals(batch.getMarineLitterCategory()) + && mlb.getMarineLitterSizeCategory().equals(batch.getMarineLitterSizeCategory())) { + + existingBatch = mlb; + batches.put(row.getBatchId(), mlb); + notImportedBatches.put(row.getBatchId(), batch); + break; + } + } + } + + if (existingBatch == null) { + batch = persistenceService.createMarineLitterBatch(batch); + batches.put(row.getBatchId(), batch); + } + + } + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + return batches; + } + + protected void importMarineLitterCatchWeights(File file, + FishingOperation operation, + MarineLitterWeightRowModel weightModel, + Map<String, Object> notImportedData) { + + Reader reader = TuttiIOUtil.newReader( + new File(file, WEIGHTS_FILE), + n_("tutti.service.multipost.import.weights.error")); + + Import<MarineLitterWeightRow> weight = Import.newImport(weightModel, reader); + + Iterator<MarineLitterWeightRow> iterator = weight.iterator(); + if (iterator.hasNext()) { + MarineLitterWeightRow row = iterator.next(); + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operation.getId()); + catchBatch.setFishingOperation(operation); + + if (catchBatch.getMarineLitterTotalWeight() == null) { + catchBatch.setMarineLitterTotalWeight(row.getTotalWeight()); + + } else if (row.getTotalWeight() != null) { + notImportedData.put(CatchBatch.PROPERTY_MARINE_LITTER_TOTAL_WEIGHT, row.getTotalWeight()); + } + + persistenceService.saveCatchBatch(catchBatch); + } + } + + //------------------------------------------------------------------------// + //-- Import individual observations --// + //------------------------------------------------------------------------// + + /** + * Import individual observation batches from a satellite post + * + * @param file the file to import the batches from + * @param operation the operation in which to add the batches + */ + public void importIndividualObservation(final File file, + final FishingOperation operation) { + + Callable<Void> call = new Callable<Void>() { + + @Override + public Void call() throws Exception { + File tempDir = TuttiIOUtil.explodeZip( + context.getConfig().getTmpDirectory(), + file, + n_("tutti.service.multipost.uncompress.error")); + + //check operation + FishingOperationRowModel operationModel = + new FishingOperationRowModel(csvSeparator); + checkSameOperation(tempDir, operationModel, operation); + + TuttiDataContext dataContext = context.getDataContext(); + List<Species> speciesList = dataContext.getReferentSpecies(); + List<Caracteristic> caracteristics = dataContext.getCaracteristicWithProtected(); + + // Import batches + // map containing the batches by their persistence id + final Map<String, IndividualObservationBatch> batches = importIndividualObservationBatches( + tempDir, + operation, + speciesList, + caracteristics); + + // Import caracteristics + + importIndividualObservationCaracteristics(file, batches, caracteristics); + + // Persist batches + + for (IndividualObservationBatch batch : batches.values()) { + persistenceService.createIndividualObservationBatch(batch); + } + + // Import attachments + + importAttachments(tempDir, batches, AttachementObjectTypeEnum.SAMPLE); + return null; + } + }; + persistenceService.invoke(call); + } + + protected Map<String, IndividualObservationBatch> importIndividualObservationBatches(File file, FishingOperation operation, + List<Species> speciesList, + List<Caracteristic> caracteristics) { + + Map<String, IndividualObservationBatch> batches = Maps.newLinkedHashMap(); + + + IndividualObservationRowModel csvModel = new IndividualObservationRowModel(csvSeparator, + speciesList, + caracteristics); + Reader reader = TuttiIOUtil.newReader( + new File(file, INDIVIDUAL_OBSERVATION_FILE), + n_("tutti.service.multipost.import.batches.error")); + + try { + Import<IndividualObservationRow> importer = Import.newImport(csvModel, reader); + + try { + for (IndividualObservationRow row : importer) { + + // create batch + IndividualObservationBatch batch = + TuttiBeanFactory.newIndividualObservationBatch(); + batch.setFishingOperation(operation); + + batch.setSpecies(row.getSpecies()); + batch.setWeight(row.getWeight()); + batch.setSize(row.getSize()); + batch.setLengthStepCaracteristic(row.getLengthStepCaracteristic()); +// batch.setSamplingCode(row.getSamplingCode()); +// batch.setCalcifiedPieceSamplingCode(row.getCalcifiedPieceSamplingCode()); + batch.setComment(row.getComment()); + batch.setCaracteristics(new CaracteristicMap()); + + batches.put(row.getBatchId(), batch); + } + + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + return batches; + } + + protected void importIndividualObservationCaracteristics(File file, Map<String, IndividualObservationBatch> batches, + List<Caracteristic> caracteristics) { + + CaracteristicRowModel caracteristicModel = new CaracteristicRowModel(csvSeparator, + caracteristics); + + Reader reader = TuttiIOUtil.newReader( + new File(file, CARACTERISTIC_FILE), + n_("tutti.service.multipost.import.caracteristics.error")); + + try { + Import<CaracteristicRow> importer = Import.newImport(caracteristicModel, reader); + + try { + for (CaracteristicRow caracteristicRow : importer) { + IndividualObservationBatch batch = batches.get(caracteristicRow.getBatchId()); + if (batch != null) { + Caracteristic caracteristic = caracteristicRow.getCaracteristic(); + Serializable value = caracteristicRow.getValue(); + + switch (caracteristic.getCaracteristicType()) { + case QUALITATIVE: + value = TuttiEntities.getQualitativeValue(caracteristic, Integer.parseInt(value.toString())); + break; + + case NUMBER: + value = Float.parseFloat(value.toString()); + break; + } + CaracteristicMap map = batch.getCaracteristics(); + map.put(caracteristic, value); + } + } + + TuttiIOUtil.close(importer, "Could not close importer"); + + } finally { + IOUtils.closeQuietly(importer); + } + + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + } + + //------------------------------------------------------------------------// + //-- Import Accidental catches --// + //------------------------------------------------------------------------// + + /** + * Import accidental catches batches from a satellite post + * + * @param file the file to import the batches from + * @param operation the operation in which to add the batches + */ + public void importAccidentalCatches(final File file, final FishingOperation operation) { + + Callable<Void> call = new Callable<Void>() { + + @Override + public Void call() throws Exception { + File tempDir = TuttiIOUtil.explodeZip( + context.getConfig().getTmpDirectory(), + file, + n_("tutti.service.multipost.uncompress.error")); + + //check operation + FishingOperationRowModel operationModel = + new FishingOperationRowModel(csvSeparator); + checkSameOperation(tempDir, operationModel, operation); + + TuttiDataContext dataContext = context.getDataContext(); + List<Species> speciesList = dataContext.getReferentSpecies(); + List<CaracteristicQualitativeValue> genderValues = dataContext.getGenderValues(); + List<Caracteristic> caracteristics = dataContext.getCaracteristicWithProtected(); + List<CaracteristicQualitativeValue> dedOrAliveValues = dataContext.getDeadOrAliveValues(); + + // Import batches + // map containing the batches by their persistence id + final Map<String, AccidentalBatch> batches = importAccidentalCatchesBatches( + tempDir, + operation, + speciesList, + genderValues, + caracteristics, + dedOrAliveValues + ); + + // Import caracteristics + + importAccidentalCatchesCaracteristics(file, batches, caracteristics); + + // Persist batches + + for (AccidentalBatch batch : batches.values()) { + persistenceService.createAccidentalBatch(batch); + } + + // Import attachments + + importAttachments(tempDir, batches, AttachementObjectTypeEnum.SAMPLE); + return null; + } + }; + persistenceService.invoke(call); + } + + protected Map<String, AccidentalBatch> importAccidentalCatchesBatches(File file, FishingOperation operation, + List<Species> speciesList, + List<CaracteristicQualitativeValue> genderValues, + List<Caracteristic> caracteristics, + List<CaracteristicQualitativeValue> dedOrAliveValues) { + + Map<String, AccidentalBatch> batches = Maps.newLinkedHashMap(); + + Reader reader = TuttiIOUtil.newReader( + new File(file, INDIVIDUAL_OBSERVATION_FILE), + n_("tutti.service.multipost.import.batches.error")); + + try { + + AccidentalCatchRowModel csvModel = new AccidentalCatchRowModel(csvSeparator, + speciesList, + genderValues, + caracteristics, + dedOrAliveValues); + + Import<AccidentalCatchRow> importer = Import.newImport(csvModel, reader); + + try { + for (AccidentalCatchRow row : importer) { + + // create batch + AccidentalBatch batch = TuttiBeanFactory.newAccidentalBatch(); + batch.setFishingOperation(operation); + + batch.setSpecies(row.getSpecies()); + batch.setGender(row.getGender()); + batch.setWeight(row.getWeight()); + batch.setSize(row.getSize()); + batch.setLengthStepCaracteristic(row.getLengthStepCaracteristic()); + batch.setDeadOrAlive(row.getDeadOrAlive()); + batch.setComment(row.getComment()); + batch.setCaracteristics(new CaracteristicMap()); + + batches.put(row.getBatchId(), batch); + } + + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + return batches; + } + + protected void importAccidentalCatchesCaracteristics(File file, Map<String, AccidentalBatch> batches, + List<Caracteristic> caracteristics) { + + CaracteristicRowModel caracteristicModel = new CaracteristicRowModel(csvSeparator, + caracteristics); + + Reader reader = TuttiIOUtil.newReader( + new File(file, CARACTERISTIC_FILE), + n_("tutti.service.multipost.import.caracteristics.error")); + + try { + Import<CaracteristicRow> importer = Import.newImport(caracteristicModel, reader); + + try { + for (CaracteristicRow caracteristicRow : importer) { + AccidentalBatch batch = batches.get(caracteristicRow.getBatchId()); + if (batch != null) { + Caracteristic caracteristic = caracteristicRow.getCaracteristic(); + Serializable value = caracteristicRow.getValue(); + + switch (caracteristic.getCaracteristicType()) { + case QUALITATIVE: + value = TuttiEntities.getQualitativeValue(caracteristic, Integer.parseInt(value.toString())); + break; + + case NUMBER: + value = Float.parseFloat(value.toString()); + break; + } + CaracteristicMap map = batch.getCaracteristics(); + map.put(caracteristic, value); + } + } + + TuttiIOUtil.close(importer, "Could not close importer"); + + } finally { + IOUtils.closeQuietly(importer); + } + + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + + } + + //------------------------------------------------------------------------// + //-- Internal methods --// + //------------------------------------------------------------------------// + + protected Pair<Integer, Serializable> getValueAndCategoryType(CatchRow row) { + + Serializable value = row.getCategoryValue(); + Integer categoryId = row.getCategoryId(); + + SampleCategoryModelEntry categoryModelEntry = + sampleCategoryModel.getCategoryById(categoryId); + + Caracteristic caracteristic = categoryModelEntry.getCaracteristic(); + if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { + CaracteristicQualitativeValue caracteristicQualitativeValue = sampleCategoryValueMap.get(String.valueOf(value)); + Preconditions.checkNotNull(caracteristicQualitativeValue, "Can't find caracteristic qualitative value with id: " + value + " for caracteristic of id: " + categoryId); + value = caracteristicQualitativeValue; + } + return Pair.of(categoryId, value); + } + + protected void checkSameOperation(File directory, + AbstractFishingOperationRowModel fishingOperationRowModel, + FishingOperation operation) { + Reader reader = TuttiIOUtil.newReader( + new File(directory, WEIGHTS_FILE), + n_("tutti.service.multipost.import.operation.error")); + + try { + Import<AbstractFishingOperationRow> importer = Import.<AbstractFishingOperationRow>newImport(fishingOperationRowModel, reader); + + Iterator<AbstractFishingOperationRow> iterator = importer.iterator(); + try { + if (iterator.hasNext()) { + AbstractFishingOperationRow row = iterator.next(); + if (ObjectUtils.notEqual(row.getStationNumber(), operation.getStationNumber()) + || ObjectUtils.notEqual(row.getOperationNumber(), operation.getFishingOperationNumber()) + || ObjectUtils.notEqual(row.getMultirigAggregation(), operation.getMultirigAggregation()) + || ObjectUtils.notEqual(row.getDate(), operation.getGearShootingStartDate())) { + + throw new TuttiBusinessException(_("tutti.service.multipost.import.wrongOperation.error", + decoratorService.getDecoratorByType(FishingOperation.class) + .toString(operation))); + } + } + } finally { + IOUtils.closeQuietly(importer); + } + } finally { + IOUtils.closeQuietly(reader); + } + } + + protected <R extends TuttiEntity> void importAttachments(File directory, + final Map<String, R> data, + final Map<String, R> notImportedData, + AttachementObjectTypeEnum objectType) { + + Function<AttachmentRow, Integer> getObjetcIdFunction = new Function<AttachmentRow, Integer>() { + @Override + public Integer apply(AttachmentRow input) { + Integer result = null; + if (notImportedData.get(input.getBatchId()) == null) { + R batch = data.get(input.getBatchId()); + if (batch != null) { + result = batch.getIdAsInt(); + } + } + return result; + } + }; + + Reader reader = TuttiIOUtil.newReader( + new File(directory, ATTACHMENTS_FILE), + n_("tutti.service.multipost.import.attachments.error")); + + try { + AttachmentRowModel attachmentModel = + new AttachmentRowModel(csvSeparator, new File(directory, ATTACHMENTS_DIRECTORY)); + Import<AttachmentRow> importer = Import.newImport(attachmentModel, reader); + + try { + for (AttachmentRow row : importer) { + Integer objectId = getObjetcIdFunction.apply(row); + if (objectId != null) { + Attachment attachment = TuttiBeanFactory.newAttachment(); + attachment.setName(row.getName()); + attachment.setComment(row.getComment()); + attachment.setObjectType(objectType); + + attachment.setObjectId(objectId); + + persistenceService.createAttachment(attachment, row.getFile()); + } + } + + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + } + + protected <R extends TuttiEntity> void importAttachments(File directory, + final Map<String, R> data, + AttachementObjectTypeEnum objectType) { + + Function<AttachmentRow, Integer> getObjetcIdFunction = new Function<AttachmentRow, Integer>() { + @Override + public Integer apply(AttachmentRow input) { + Integer result = null; + R batch = data.get(input.getBatchId()); + if (batch != null) { + result = batch.getIdAsInt(); + } + return result; + } + }; + + Reader reader = TuttiIOUtil.newReader( + new File(directory, ATTACHMENTS_FILE), + n_("tutti.service.multipost.import.attachments.error")); + + try { + AttachmentRowModel attachmentModel = + new AttachmentRowModel(csvSeparator, new File(directory, ATTACHMENTS_DIRECTORY)); + Import<AttachmentRow> importer = Import.newImport(attachmentModel, reader); + + try { + for (AttachmentRow row : importer) { + Integer objectId = getObjetcIdFunction.apply(row); + if (objectId != null) { + Attachment attachment = TuttiBeanFactory.newAttachment(); + attachment.setName(row.getName()); + attachment.setComment(row.getComment()); + attachment.setObjectType(objectType); + + attachment.setObjectId(objectId); + + persistenceService.createAttachment(attachment, row.getFile()); + } + } + + TuttiIOUtil.close(importer, "Could not close importer"); + } finally { + IOUtils.closeQuietly(importer); + } + + TuttiIOUtil.close(reader, "Could not close reader"); + } finally { + IOUtils.closeQuietly(reader); + } + } + +} Deleted: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,681 +0,0 @@ -package fr.ifremer.tutti.service.catches.multipost; - -/* - * #%L - * Tutti :: Service - * $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 com.google.common.io.Files; -import fr.ifremer.tutti.TuttiIOUtil; -import fr.ifremer.tutti.TuttiTechnicalException; -import fr.ifremer.tutti.persistence.entities.CaracteristicMap; -import fr.ifremer.tutti.persistence.entities.data.AccidentalBatch; -import fr.ifremer.tutti.persistence.entities.data.AttachementObjectTypeEnum; -import fr.ifremer.tutti.persistence.entities.data.Attachment; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; -import fr.ifremer.tutti.persistence.entities.data.CatchBatch; -import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.data.IndividualObservationBatch; -import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; -import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; -import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; -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.service.AbstractTuttiService; -import fr.ifremer.tutti.service.DecoratorService; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.apache.commons.io.IOUtils; -import org.nuiton.csv.Export; -import org.nuiton.csv.ExportModel; - -import java.io.File; -import java.io.Writer; -import java.util.List; -import java.util.Map; - -import static org.nuiton.i18n.I18n._; -import static org.nuiton.i18n.I18n.n_; - -/** - * Service to export batches from a satellite post into a master post. - * - * @author kmorin <kmorin@codelutin.com> - * @author tchemit <chemit@codelutin.com> - * @since 2.2 - */ -public class TuttiMultiPostExportService extends AbstractTuttiService { - -// private static final Log log = -// LogFactory.getLog(TuttiMultiPostImportExportService.class); - - public static final String BATCHES_KEY = "batchesKey"; - - protected static final String ATTACHMENTS_DIRECTORY = "attachments"; - - protected static final String ATTACHMENTS_FILE = "attachments.csv"; - - protected static final String SPECIES_FILE = "species.csv"; - - protected static final String BENTHOS_FILE = "benthos.csv"; - - protected static final String MARINE_LITTER_FILE = "marineLitter.csv"; - - protected static final String INDIVIDUAL_OBSERVATION_FILE = "individualObservation.csv"; - - protected static final String ACCIDENTAL_CATCHES_FILE = "accidentalCatches.csv"; - - protected static final String FREQUENCIES_FILE = "frequencies.csv"; - - protected static final String CARACTERISTIC_FILE = "caracteristics.csv"; - - protected static final String WEIGHTS_FILE = "weights.csv"; - - protected PersistenceService persistenceService; - - protected DecoratorService decoratorService; - - protected char csvSeparator; - - protected SampleCategoryModel sampleCategoryModel; - - protected Map<String, CaracteristicQualitativeValue> sampleCategoryValueMap; - - @Override - public void setServiceContext(TuttiServiceContext context) { - super.setServiceContext(context); - persistenceService = getService(PersistenceService.class); - decoratorService = getService(DecoratorService.class); - - csvSeparator = context.getConfig().getCsvSeparator(); - - sampleCategoryModel = context.getSampleCategoryModel(); - - sampleCategoryValueMap = Maps.newTreeMap(); - - for (SampleCategoryModelEntry sampleCategoryModelEntry : sampleCategoryModel.getCategory()) { - Caracteristic caracteristic = sampleCategoryModelEntry.getCaracteristic(); - if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { - List<CaracteristicQualitativeValue> qualitativeValue = caracteristic.getQualitativeValue(); - for (CaracteristicQualitativeValue value : qualitativeValue) { - sampleCategoryValueMap.put(value.getId(), value); - } - } - } - } - - /** - * Export species batches. - * - * @param file the file to export the batches into - * @param operation the operation to export - */ - public void exportSpecies(File file, FishingOperation operation) { - - String operationId = operation.getId(); - if (persistenceService.isFishingOperationWithCatchBatch(operationId)) { - - // create rows - - BatchContainer<SpeciesBatch> speciesBatchContainer = - persistenceService.getRootSpeciesBatch(operationId, null); - - List<CatchRow> rows = Lists.newArrayList(); - List<CatchFrequencyRow> frequencyRows = Lists.newArrayList(); - List<AttachmentRow> attachmentRows = Lists.newArrayList(); - - for (SpeciesBatch batch : speciesBatchContainer.getChildren()) { - createSpeciesRow(batch, null, rows, frequencyRows, attachmentRows); - } - - // export catches + weights + attachments - - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operationId); - CatchWeightsRow weights = new CatchWeightsRow(); - weights.setTotalSortedWeight(catchBatch.getSpeciesTotalSortedWeight()); - weights.setInertWeight(catchBatch.getSpeciesTotalInertWeight()); - weights.setLivingNotItemizedWeight(catchBatch.getSpeciesTotalLivingNotItemizedWeight()); - exportOperation(weights, operation); - - exportCatches(file, - SPECIES_FILE, - weights, - rows, - frequencyRows, - attachmentRows); - } - } - - /** - * Export benthos batches. - * - * @param file the file to export the batches into - * @param operation the operation to export - */ - public void exportBenthos(File file, FishingOperation operation) { - - String operationId = operation.getId(); - if (persistenceService.isFishingOperationWithCatchBatch(operationId)) { - - BatchContainer<BenthosBatch> benthosBatchContainer = - persistenceService.getRootBenthosBatch(operationId, null); - - // create rows - - List<CatchRow> rows = Lists.newArrayList(); - List<CatchFrequencyRow> frequencyRows = Lists.newArrayList(); - List<AttachmentRow> attachmentRows = Lists.newArrayList(); - - for (BenthosBatch batch : benthosBatchContainer.getChildren()) { - createBenthosRow(batch, null, rows, frequencyRows, attachmentRows); - } - - // export catches + weights + attachments - - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operationId); - CatchWeightsRow weights = new CatchWeightsRow(); - weights.setTotalSortedWeight(catchBatch.getBenthosTotalSortedWeight()); - weights.setInertWeight(catchBatch.getBenthosTotalInertWeight()); - weights.setLivingNotItemizedWeight(catchBatch.getBenthosTotalLivingNotItemizedWeight()); - exportOperation(weights, operation); - - exportCatches(file, - BENTHOS_FILE, - weights, - rows, - frequencyRows, - attachmentRows); - } - } - - /** - * Export marine litter batches. - * - * @param file the file to export the batches into - * @param operation the operation to export - */ - public void exportMarineLitter(File file, FishingOperation operation) { - - String operationId = operation.getId(); - if (persistenceService.isFishingOperationWithCatchBatch(operationId)) { - - // create rows - - BatchContainer<MarineLitterBatch> marineLitterBatchContainer = - persistenceService.getRootMarineLitterBatch(operationId); - - List<MarineLitterRow> rows = Lists.newArrayList(); - List<AttachmentRow> attachmentRows = Lists.newArrayList(); - - for (MarineLitterBatch batch : marineLitterBatchContainer.getChildren()) { - MarineLitterRow row = new MarineLitterRow(); - - String id = context.generateId(MarineLitterRow.class); - row.setBatchId(id); - - row.setCategory(batch.getMarineLitterCategory()); - row.setSizeCategory(batch.getMarineLitterSizeCategory()); - row.setNumber(batch.getNumber()); - row.setWeight(batch.getWeight()); - row.setComment(batch.getComment()); - - rows.add(row); - - addAttachments(id, - batch.getIdAsInt(), - AttachementObjectTypeEnum.BATCH, - attachmentRows); - } - - - File directory = Files.createTempDir(); - List<File> file2zip = Lists.newArrayList(); - - // export marine litters - - MarineLitterRowModel marineLitterRowModel = new MarineLitterRowModel(csvSeparator); - File marineLitterFile = new File(directory, MARINE_LITTER_FILE); - file2zip.add(marineLitterFile); - export(marineLitterFile, - marineLitterRowModel, - rows, - n_("tutti.service.multipost.export.batches.error")); - - // export weights - - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operationId); - MarineLitterWeightRow weight = new MarineLitterWeightRow(); - weight.setTotalWeight(catchBatch.getMarineLitterTotalWeight()); - exportOperation(weight, operation); - - MarineLitterWeightRowModel weightModel = new MarineLitterWeightRowModel(csvSeparator); - - File weightFile = new File(directory, WEIGHTS_FILE); - file2zip.add(weightFile); - export(weightFile, - weightModel, - Lists.newArrayList(weight), - n_("tutti.service.multipost.export.weight.error")); - - // export attachments + create final zip - - exportAttachmentsAndCreateZip(file, - directory, - file2zip, - attachmentRows); - } - } - - /** - * Export individual observation batches. - * - * @param file the file to export the batches into - * @param operation the operation to export - */ - public void exportIndividualObservation(File file, FishingOperation operation) { - List<IndividualObservationBatch> individualObservations = - persistenceService.getAllIndividualObservationBatch(operation.getId()); - - // create rows - - List<IndividualObservationRow> rows = Lists.newArrayList(); - List<CaracteristicRow> caracteristicRows = Lists.newArrayList(); - List<AttachmentRow> attachmentRows = Lists.newArrayList(); - - - for (IndividualObservationBatch batch : individualObservations) { - IndividualObservationRow row = new IndividualObservationRow(); - - String id = context.generateId(IndividualObservationRow.class); - row.setBatchId(id); - - row.setSpecies(batch.getSpecies()); - row.setWeight(batch.getWeight()); - row.setSize(batch.getSize()); - row.setLengthStepCaracteristic(batch.getLengthStepCaracteristic()); -// row.setSamplingCode(batch.getSamplingCode()); -// row.setCalcifiedPieceSamplingCode(batch.getCalcifiedPieceSamplingCode()); - row.setComment(batch.getComment()); - - rows.add(row); - - CaracteristicMap caracteristicMap = batch.getCaracteristics(); - for (Caracteristic caracteristic : caracteristicMap.keySet()) { - CaracteristicRow caracteristicRow = new CaracteristicRow(); - caracteristicRow.setBatchId(id); - caracteristicRow.setCaracteristic(caracteristic); - caracteristicRow.setValue(caracteristicMap.get(caracteristic)); - caracteristicRows.add(caracteristicRow); - } - - addAttachments(id, batch.getIdAsInt(), AttachementObjectTypeEnum.SAMPLE, attachmentRows); - } - - File directory = Files.createTempDir(); - List<File> file2zip = Lists.newArrayList(); - - // export individual observations - - IndividualObservationRowModel csvModel = new IndividualObservationRowModel(csvSeparator); - File individualObservationFile = new File(directory, INDIVIDUAL_OBSERVATION_FILE); - file2zip.add(individualObservationFile); - export(individualObservationFile, - csvModel, - rows, - n_("tutti.service.multipost.export.batches.error")); - - // export caracteristics - - CaracteristicRowModel caracteristicCsvModel = new CaracteristicRowModel(csvSeparator); - File caracteristicFile = new File(directory, CARACTERISTIC_FILE); - file2zip.add(caracteristicFile); - export(caracteristicFile, - caracteristicCsvModel, - caracteristicRows, - n_("tutti.service.multipost.export.batches.error")); - - // export operation - - FishingOperationRow foRow = new FishingOperationRow(); - exportOperation(foRow, operation); - - FishingOperationRowModel foRowModel = new FishingOperationRowModel(csvSeparator); - - File weightFile = new File(directory, WEIGHTS_FILE); - file2zip.add(weightFile); - export(weightFile, - foRowModel, - Lists.newArrayList(foRow), - n_("tutti.service.multipost.export.operation.error")); - - // export attachments + create final zip - - exportAttachmentsAndCreateZip(file, - directory, - file2zip, - attachmentRows); - } - - /** - * Export accidental catch batches. - * - * @param file the file to export the batches into - * @param operation the operation to export - */ - public void exportAccidentalCatch(File file, FishingOperation operation) { - List<AccidentalBatch> accidentalCatches = - persistenceService.getAllAccidentalBatch(operation.getId()); - - List<AccidentalCatchRow> rows = Lists.newArrayList(); - List<CaracteristicRow> caracteristicRows = Lists.newArrayList(); - List<AttachmentRow> attachmentRows = Lists.newArrayList(); - - // create rows - - for (AccidentalBatch batch : accidentalCatches) { - AccidentalCatchRow row = new AccidentalCatchRow(); - - String id = context.generateId(AccidentalCatchRow.class); - row.setBatchId(id); - - row.setSpecies(batch.getSpecies()); - row.setGender(batch.getGender()); - row.setWeight(batch.getWeight()); - row.setSize(batch.getSize()); - row.setLengthStepCaracteristic(batch.getLengthStepCaracteristic()); - row.setDeadOrAlive(batch.getDeadOrAlive()); - row.setComment(batch.getComment()); - - rows.add(row); - - CaracteristicMap caracteristicMap = batch.getCaracteristics(); - for (Caracteristic caracteristic : caracteristicMap.keySet()) { - CaracteristicRow caracteristicRow = new CaracteristicRow(); - caracteristicRow.setBatchId(id); - caracteristicRow.setCaracteristic(caracteristic); - caracteristicRow.setValue(caracteristicMap.get(caracteristic)); - caracteristicRows.add(caracteristicRow); - } - - addAttachments(id, batch.getIdAsInt(), AttachementObjectTypeEnum.SAMPLE, attachmentRows); - } - - // export accidental catches - - AccidentalCatchRowModel csvModel = new AccidentalCatchRowModel(csvSeparator); - - File directory = Files.createTempDir(); - List<File> file2zip = Lists.newArrayList(); - - File accidentalCatchesFile = new File(directory, ACCIDENTAL_CATCHES_FILE); - file2zip.add(accidentalCatchesFile); - export(accidentalCatchesFile, - csvModel, - rows, - n_("tutti.service.multipost.export.batches.error")); - - // export caracteristics - - CaracteristicRowModel caracteristicCsvModel = new CaracteristicRowModel(csvSeparator); - File caracteristicFile = new File(directory, CARACTERISTIC_FILE); - file2zip.add(caracteristicFile); - export(caracteristicFile, - caracteristicCsvModel, - caracteristicRows, - n_("tutti.service.multipost.export.batches.error")); - - // export operation - - FishingOperationRow foRow = new FishingOperationRow(); - exportOperation(foRow, operation); - - FishingOperationRowModel foRowModel = new FishingOperationRowModel(csvSeparator); - - File weightFile = new File(directory, WEIGHTS_FILE); - file2zip.add(weightFile); - export(weightFile, - foRowModel, - Lists.newArrayList(foRow), - n_("tutti.service.multipost.export.operation.error")); - - // export attachments + create final zip - - exportAttachmentsAndCreateZip(file, - directory, - file2zip, - attachmentRows); - } - - //------------------------------------------------------------------------// - //-- Internal methods --// - //------------------------------------------------------------------------// - - protected void exportCatches(File file, - String batchFile, - CatchWeightsRow weights, - List<CatchRow> rows, - List<CatchFrequencyRow> frequencyRows, - List<AttachmentRow> attachmentRows) { - CatchRowModel csvModel = new CatchRowModel(csvSeparator); - CatchFrequencyRowModel csvFrequencyModel = new CatchFrequencyRowModel(csvSeparator); - CatchWeightsRowModel catchWeightsModel = new CatchWeightsRowModel(csvSeparator); - - File directory = Files.createTempDir(); - List<File> file2zip = Lists.newArrayList(); - - File weightsFile = new File(directory, WEIGHTS_FILE); - file2zip.add(weightsFile); - export(weightsFile, - catchWeightsModel, - Lists.newArrayList(weights), - n_("tutti.service.multipost.export.weights.error")); - - File speciesFile = new File(directory, batchFile); - file2zip.add(speciesFile); - export(speciesFile, - csvModel, - rows, - n_("tutti.service.multipost.export.batches.error")); - - File frequencyFile = new File(directory, FREQUENCIES_FILE); - file2zip.add(frequencyFile); - export(frequencyFile, - csvFrequencyModel, - frequencyRows, - n_("tutti.service.multipost.export.frequencies.error")); - - // export attachments + create final zip - - exportAttachmentsAndCreateZip(file, - directory, - file2zip, - attachmentRows); - } - - protected void createSpeciesRow(SpeciesBatch batch, - String parentId, - List<CatchRow> rows, - List<CatchFrequencyRow> frequencyRows, - List<AttachmentRow> attachmentRows) { - CatchRow row = new CatchRow(); - - String id = context.generateId(CatchRow.class); - row.setId(id); - row.setParentId(parentId); - row.setSpecies(batch.getSpecies()); - - row.setCategoryId(batch.getSampleCategoryId()); - row.setCategoryValue(batch.getSampleCategoryValue()); - row.setCategoryWeight(batch.getSampleCategoryWeight()); - row.setWeight(batch.getWeight()); - row.setNumber(batch.getNumber()); - row.setComment(batch.getComment()); - row.setToConfirm(batch.isSpeciesToConfirm()); - - rows.add(row); - - addFrequencies(id, batch.getId(), frequencyRows); - addAttachments(id, batch.getIdAsInt(), AttachementObjectTypeEnum.BATCH, attachmentRows); - - for (SpeciesBatch child : batch.getChildBatchs()) { - createSpeciesRow(child, id, rows, frequencyRows, attachmentRows); - } - } - - protected void createBenthosRow(BenthosBatch batch, - String parentId, - List<CatchRow> rows, - List<CatchFrequencyRow> frequencyRows, - List<AttachmentRow> attachmentRows) { - CatchRow row = new CatchRow(); - - String id = context.generateId(CatchRow.class); - row.setId(id); - row.setParentId(parentId); - row.setSpecies(batch.getSpecies()); - - row.setCategoryId(batch.getSampleCategoryId()); - row.setCategoryValue(batch.getSampleCategoryValue()); - row.setCategoryWeight(batch.getSampleCategoryWeight()); - row.setWeight(batch.getWeight()); - row.setNumber(batch.getNumber()); - row.setComment(batch.getComment()); - row.setToConfirm(batch.isSpeciesToConfirm()); - - rows.add(row); - - addFrequencies(id, batch.getId(), frequencyRows); - addAttachments(id, batch.getIdAsInt(), AttachementObjectTypeEnum.BATCH, attachmentRows); - - for (BenthosBatch child : batch.getChildBatchs()) { - createBenthosRow(child, id, rows, frequencyRows, attachmentRows); - } - } - - protected void exportOperation(AbstractFishingOperationRow afoRow, FishingOperation operation) { - afoRow.setStationNumber(operation.getStationNumber()); - afoRow.setOperationNumber(operation.getFishingOperationNumber()); - afoRow.setMultirigAggregation(operation.getMultirigAggregation()); - afoRow.setDate(operation.getGearShootingStartDate()); - } - - protected void addFrequencies(String rowId, - String batchId, - List<CatchFrequencyRow> frequencyRows) { - List<SpeciesBatchFrequency> frequencies = - persistenceService.getAllSpeciesBatchFrequency(batchId); - for (SpeciesBatchFrequency frequency : frequencies) { - CatchFrequencyRow frequencyRow = new CatchFrequencyRow(); - frequencyRow.setBatchId(rowId); - frequencyRow.setLengthStepCaracteristic(frequency.getLengthStepCaracteristic()); - frequencyRow.setLengthStep(frequency.getLengthStep()); - frequencyRow.setNumber(frequency.getNumber()); - frequencyRow.setWeight(frequency.getWeight()); - frequencyRows.add(frequencyRow); - } - } - - protected void addAttachments(String batchId, - int objectId, - AttachementObjectTypeEnum objectType, - List<AttachmentRow> attachmentRows) { - List<Attachment> attachments = - persistenceService.getAllAttachments(objectType, objectId); - for (Attachment attachment : attachments) { - AttachmentRow attachmentRow = new AttachmentRow(); - attachmentRow.setBatchId(batchId); - attachmentRow.setName(attachment.getName()); - attachmentRow.setComment(attachment.getComment()); - attachmentRow.setFile(persistenceService.getAttachmentFile(attachment.getId())); - attachmentRows.add(attachmentRow); - } - } - - - protected <R> void export(File file, - ExportModel<R> exportModel, - List<R> rows, - String errorMessage) { - Writer writer = TuttiIOUtil.newWriter( - file, - n_("tutti.service.multipost.export.file.writer.error")); - try { - Export export = Export.newExport(exportModel, rows); - export.write(writer); - writer.close(); - - } catch (Exception e) { - throw new TuttiTechnicalException(_(errorMessage, file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - protected void exportAttachments(File directory, - List<File> file2zip, - List<AttachmentRow> attachmentRows) { - - AttachmentRowModel csvAttachmentModel = new AttachmentRowModel(csvSeparator); - - File attachmentDirectory = new File(directory, ATTACHMENTS_DIRECTORY); - TuttiIOUtil.forceMkdir(attachmentDirectory, _("tutti.service.multipost.attachment.mkdir.error", attachmentDirectory)); - file2zip.add(attachmentDirectory); - for (AttachmentRow attachmentRow : attachmentRows) { - File attachmentFile = attachmentRow.getFile(); - File destFile = new File(attachmentDirectory, attachmentFile.getName()); - TuttiIOUtil.copyFile(attachmentFile, - destFile, - _("tutti.service.multipost.attachment.copy.error", attachmentFile)); - file2zip.add(destFile); - } - - File attachmentFile = new File(directory, ATTACHMENTS_FILE); - file2zip.add(attachmentFile); - export(attachmentFile, - csvAttachmentModel, - attachmentRows, - n_("tutti.service.multipost.export.attachments.error")); - - } - - protected void exportAttachmentsAndCreateZip(File file, - File directory, - List<File> file2zip, - List<AttachmentRow> attachmentRows) { - exportAttachments(directory, file2zip, attachmentRows); - - try { - TuttiIOUtil.zip(directory, - file, - file2zip, - n_("tutti.service.multipost.export.error")); - } finally { - TuttiIOUtil.deleteDirectory(directory, _("tutti.service.multipost.export.deleteTempDirectory.error", file)); - } - } -} Deleted: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostImportService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostImportService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostImportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,1321 +0,0 @@ -package fr.ifremer.tutti.service.catches.multipost; - -/* - * #%L - * Tutti :: Service - * $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.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Maps; -import fr.ifremer.tutti.TuttiBusinessException; -import fr.ifremer.tutti.TuttiIOUtil; -import fr.ifremer.tutti.persistence.entities.CaracteristicMap; -import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; -import fr.ifremer.tutti.persistence.entities.TuttiEntities; -import fr.ifremer.tutti.persistence.entities.TuttiEntity; -import fr.ifremer.tutti.persistence.entities.data.AccidentalBatch; -import fr.ifremer.tutti.persistence.entities.data.AttachementObjectTypeEnum; -import fr.ifremer.tutti.persistence.entities.data.Attachment; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatchFrequency; -import fr.ifremer.tutti.persistence.entities.data.CatchBatch; -import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.data.IndividualObservationBatch; -import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; -import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; -import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; -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.service.AbstractTuttiService; -import fr.ifremer.tutti.service.DecoratorService; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.TuttiDataContext; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.nuiton.csv.Import; - -import java.io.File; -import java.io.Reader; -import java.io.Serializable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; - -import static org.nuiton.i18n.I18n._; -import static org.nuiton.i18n.I18n.n_; - -/** - * Service to export batches from a satellite post or import batches - * into a master post. - * - * @author kmorin <kmorin@codelutin.com> - * @since 2.2 - */ -public class TuttiMultiPostImportService extends AbstractTuttiService { - -// private static final Log log = -// LogFactory.getLog(TuttiMultiPostImportExportService.class); - - public static final String BATCHES_KEY = "batchesKey"; - - protected static final String ATTACHMENTS_DIRECTORY = "attachments"; - - protected static final String ATTACHMENTS_FILE = "attachments.csv"; - - protected static final String SPECIES_FILE = "species.csv"; - - protected static final String BENTHOS_FILE = "benthos.csv"; - - protected static final String MARINE_LITTER_FILE = "marineLitter.csv"; - - protected static final String INDIVIDUAL_OBSERVATION_FILE = "individualObservation.csv"; - - protected static final String ACCIDENTAL_CATCHES_FILE = "accidentalCatches.csv"; - - protected static final String FREQUENCIES_FILE = "frequencies.csv"; - - protected static final String CARACTERISTIC_FILE = "caracteristics.csv"; - - protected static final String WEIGHTS_FILE = "weights.csv"; - - protected PersistenceService persistenceService; - - protected DecoratorService decoratorService; - - protected char csvSeparator; - - protected SampleCategoryModel sampleCategoryModel; - - protected Map<String, CaracteristicQualitativeValue> sampleCategoryValueMap; - - @Override - public void setServiceContext(TuttiServiceContext context) { - super.setServiceContext(context); - persistenceService = getService(PersistenceService.class); - decoratorService = getService(DecoratorService.class); - - csvSeparator = context.getConfig().getCsvSeparator(); - - sampleCategoryModel = context.getSampleCategoryModel(); - - sampleCategoryValueMap = Maps.newTreeMap(); - - for (SampleCategoryModelEntry sampleCategoryModelEntry : sampleCategoryModel.getCategory()) { - Caracteristic caracteristic = sampleCategoryModelEntry.getCaracteristic(); - if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { - List<CaracteristicQualitativeValue> qualitativeValue = caracteristic.getQualitativeValue(); - for (CaracteristicQualitativeValue value : qualitativeValue) { - sampleCategoryValueMap.put(value.getId(), value); - } - } - } - } - - //------------------------------------------------------------------------// - //-- Import Species --// - //------------------------------------------------------------------------// - - /** - * Import species batches from a satellite post - * - * @param file the file to import the batches from - * @param operation the operation in which to add the batches - * @return the list of the species which have not been imported, because there were concurrent batches - */ - public Map<String, Object> importSpecies(final File file, - final FishingOperation operation) { - - Callable<Map<String, Object>> call = new Callable<Map<String, Object>>() { - - @Override - public Map<String, Object> call() throws Exception { - - File tempDir = TuttiIOUtil.explodeZip( - context.getConfig().getTmpDirectory(), - file, - n_("tutti.service.multipost.uncompress.error")); - - //check operation - CatchWeightsRowModel weightsModel = new CatchWeightsRowModel(csvSeparator); - checkSameOperation(tempDir, weightsModel, operation); - - final Map<String, Object> notImportedData = Maps.newHashMap(); - - final Map<String, SpeciesBatch> notImportedBatches = Maps.newLinkedHashMap(); - - BatchContainer<SpeciesBatch> speciesBatches = - persistenceService.getRootSpeciesBatch(operation.getId(), null); - - TuttiDataContext dataContext = context.getDataContext(); - List<Species> speciesList = dataContext.getReferentSpecies(); - - // Import batches - // map containing the batches by their persistence id - - final Map<String, SpeciesBatch> batches = importSpeciesBatches( - tempDir, - operation, - speciesBatches, - notImportedBatches, - speciesList); - - List<Caracteristic> caracteristics = dataContext.getCaracteristics(); - - // Import frequencies - - importSpeciesFrequencies( - tempDir, - batches, - notImportedBatches, - caracteristics); - - // Import attachments - - importAttachments(tempDir, - batches, - notImportedBatches, - AttachementObjectTypeEnum.BATCH); - - // Import weights - - importSpeciesWeights(tempDir, - operation, - weightsModel, - notImportedData); - - notImportedData.put(BATCHES_KEY, notImportedBatches.values()); - - return notImportedData; - } - }; - - Map<String, Object> result = persistenceService.invoke(call); - return result; - } - - protected Map<String, SpeciesBatch> importSpeciesBatches(File file, - FishingOperation operation, - BatchContainer<SpeciesBatch> speciesBatches, - Map<String, SpeciesBatch> notImportedBatches, - List<Species> speciesList) { - final Map<String, SpeciesBatch> batches = Maps.newHashMap(); - - Reader reader = TuttiIOUtil.newReader( - new File(file, SPECIES_FILE), - n_("tutti.service.multipost.import.batches.error")); - - try { - CatchRowModel csvModel = new CatchRowModel(csvSeparator, - speciesList); - - Import<CatchRow> importer = Import.newImport(csvModel, reader); - - try { - for (CatchRow row : importer) { - - // create batch - SpeciesBatch batch = TuttiBeanFactory.newSpeciesBatch(); - batch.setFishingOperation(operation); - - Species species = row.getSpecies(); - batch.setSpecies(row.getSpecies()); - batch.setWeight(row.getWeight()); - batch.setNumber(row.getNumber()); - batch.setComment(row.getComment()); - batch.setSpeciesToConfirm(row.isToConfirm()); - - Pair<Integer, Serializable> valueAndCategoryType = getValueAndCategoryType(row); - Integer categoryId = valueAndCategoryType.getKey(); - Serializable value = valueAndCategoryType.getValue(); - - batch.setSampleCategoryId(categoryId); - batch.setSampleCategoryValue(value); - batch.setSampleCategoryWeight(row.getCategoryWeight()); - - // get parent batch - String parentId = row.getParentId(); - String parentPersistedId = null; - SpeciesBatch parent = null; - if (StringUtils.isNotEmpty(parentId)) { - parent = batches.get(parentId); - parentPersistedId = parent.getId(); - } - - SpeciesBatch existingBatch = null; - List<SpeciesBatch> batchesToBrowse; - if (parent == null) { - batchesToBrowse = speciesBatches.getChildren(); - } else { - batchesToBrowse = parent.getChildBatchs(); - } - - // check if the parent has already a batch with the caracteristic value - // and if the children batch are categorized with the same caracterstic - if (batchesToBrowse != null) { - for (SpeciesBatch sb : batchesToBrowse) { - if (sb.getSpecies().equals(species) - && (!sb.getSampleCategoryId().equals(batch.getSampleCategoryId()) - || sb.getSampleCategoryValue().equals(value))) { - - existingBatch = sb; - batches.put(row.getId(), sb); - notImportedBatches.put(row.getId(), batch); - break; - } - } - } - - if (existingBatch == null) { - batch = persistenceService.createSpeciesBatch(batch, parentPersistedId); - batches.put(row.getId(), batch); - } - } - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - return batches; - } - - protected void importSpeciesFrequencies( - File file, - Map<String, SpeciesBatch> batches, - Map<String, SpeciesBatch> notImportedBatches, - List<Caracteristic> caracteristics) { - ListMultimap<String, SpeciesBatchFrequency> frequencyMap = - ArrayListMultimap.create(); - - Reader reader = TuttiIOUtil.newReader( - new File(file, FREQUENCIES_FILE), - n_("tutti.service.multipost.import.frequencies.error")); - - try { - - CatchFrequencyRowModel frequencyModel = new CatchFrequencyRowModel(csvSeparator, - caracteristics); - - Import<CatchFrequencyRow> importer = Import.newImport(frequencyModel, reader); - - try { - for (CatchFrequencyRow frequencyRow : importer) { - if (notImportedBatches.get(frequencyRow.getBatchId()) == null) { - SpeciesBatch batch = batches.get(frequencyRow.getBatchId()); - if (batch != null) { - SpeciesBatchFrequency frequency = TuttiBeanFactory.newSpeciesBatchFrequency(); - frequency.setLengthStepCaracteristic(frequencyRow.getLengthStepCaracteristic()); - frequency.setLengthStep(frequencyRow.getLengthStep()); - frequency.setNumber(frequencyRow.getNumber()); - frequency.setWeight(frequencyRow.getWeight()); - frequency.setBatch(batch); - frequencyMap.put(batch.getId(), frequency); - } - } - } - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - - for (String batchId : frequencyMap.keySet()) { - List<SpeciesBatchFrequency> frequencies = frequencyMap.get(batchId); - persistenceService.saveSpeciesBatchFrequency(batchId, frequencies); - } - } - - protected void importSpeciesWeights(File file, - FishingOperation operation, - CatchWeightsRowModel weightsModel, - Map<String, Object> notImportedData) { - Reader reader = TuttiIOUtil.newReader( - new File(file, WEIGHTS_FILE), - n_("tutti.service.multipost.import.weights.error")); - - try { - Import<CatchWeightsRow> importer = Import.newImport(weightsModel, reader); - - try { - Iterator<CatchWeightsRow> iterator = importer.iterator(); - if (iterator.hasNext()) { - CatchWeightsRow row = iterator.next(); - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operation.getId()); - catchBatch.setFishingOperation(operation); - - if (catchBatch.getSpeciesTotalSortedWeight() == null) { - catchBatch.setSpeciesTotalSortedWeight(row.getTotalSortedWeight()); - - } else if (row.getTotalSortedWeight() != null) { - notImportedData.put(CatchBatch.PROPERTY_SPECIES_TOTAL_SORTED_WEIGHT, row.getTotalSortedWeight()); - } - - if (catchBatch.getSpeciesTotalInertWeight() == null) { - catchBatch.setSpeciesTotalInertWeight(row.getInertWeight()); - - } else if (row.getInertWeight() != null) { - notImportedData.put(CatchBatch.PROPERTY_SPECIES_TOTAL_INERT_WEIGHT, row.getInertWeight()); - } - - if (catchBatch.getSpeciesTotalLivingNotItemizedWeight() == null) { - catchBatch.setSpeciesTotalLivingNotItemizedWeight(row.getLivingNotItemizedWeight()); - - } else if (row.getLivingNotItemizedWeight() != null) { - notImportedData.put(CatchBatch.PROPERTY_SPECIES_TOTAL_LIVING_NOT_ITEMIZED_WEIGHT, - row.getLivingNotItemizedWeight()); - } - persistenceService.saveCatchBatch(catchBatch); - } - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - } - - //------------------------------------------------------------------------// - //-- Import Benthos --// - //------------------------------------------------------------------------// - - /** - * Import benthos batches from a satellite post - * - * @param file the file to import the batches from - * @param operation the operation in which to add the batches - * @return the list of the benthos which have not been imported, because there were concurrent batches - */ - public Map<String, Object> importBenthos(final File file, - final FishingOperation operation) { - - Callable<Map<String, Object>> call = new Callable<Map<String, Object>>() { - - @Override - public Map<String, Object> call() throws Exception { - - File tempDir = TuttiIOUtil.explodeZip( - context.getConfig().getTmpDirectory(), - file, - n_("tutti.service.multipost.uncompress.error")); - - //check operation - CatchWeightsRowModel weightsModel = new CatchWeightsRowModel(csvSeparator); - checkSameOperation(tempDir, weightsModel, operation); - - Map<String, Object> notImportedData = Maps.newHashMap(); - final Map<String, BenthosBatch> notImportedBatches = Maps.newLinkedHashMap(); - - BatchContainer<BenthosBatch> benthosBatches = - persistenceService.getRootBenthosBatch(operation.getId(), null); - - TuttiDataContext dataContext = context.getDataContext(); - List<Species> speciesList = dataContext.getReferentSpecies(); - - // Import batches - // map containing the batches by their persistence id - final Map<String, BenthosBatch> batches = importBenthosBatches( - tempDir, - operation, - benthosBatches, - notImportedBatches, - speciesList); - - // Import frequencies - - importBenthosFrequencies( - tempDir, - batches, - notImportedBatches, - dataContext.getCaracteristics()); - - // Import attachments - - importAttachments(tempDir, - batches, - notImportedBatches, - AttachementObjectTypeEnum.BATCH); - - // Import weights - - importBenthosWeights(tempDir, - operation, - weightsModel, - notImportedData); - - notImportedData.put(BATCHES_KEY, notImportedBatches.values()); - return notImportedData; - } - }; - - Map<String, Object> result = persistenceService.invoke(call); - return result; - } - - protected Map<String, BenthosBatch> importBenthosBatches(File file, - FishingOperation operation, - BatchContainer<BenthosBatch> benthosBatches, - Map<String, BenthosBatch> notImportedBatches, - List<Species> speciesList) { - final Map<String, BenthosBatch> batches = Maps.newHashMap(); - Reader reader = TuttiIOUtil.newReader( - new File(file, BENTHOS_FILE), - n_("tutti.service.multipost.import.batches.error")); - - try { - CatchRowModel csvModel = new CatchRowModel(csvSeparator, - speciesList); - - Import<CatchRow> importer = Import.newImport(csvModel, reader); - - try { - for (CatchRow row : importer) { - - // create batch - BenthosBatch batch = TuttiBeanFactory.newBenthosBatch(); - batch.setFishingOperation(operation); - - Species species = row.getSpecies(); - batch.setSpecies(row.getSpecies()); - batch.setWeight(row.getWeight()); - batch.setNumber(row.getNumber()); - batch.setComment(row.getComment()); - batch.setSpeciesToConfirm(row.isToConfirm()); - - Pair<Integer, Serializable> valueAndCategoryType = getValueAndCategoryType(row); - Integer categoryId = valueAndCategoryType.getKey(); - Serializable value = valueAndCategoryType.getValue(); - - batch.setSampleCategoryId(categoryId); - batch.setSampleCategoryValue(value); - batch.setSampleCategoryWeight(row.getCategoryWeight()); - - // get parent batch - String parentId = row.getParentId(); - String parentPersistedId = null; - BenthosBatch parent = null; - if (StringUtils.isNotEmpty(parentId)) { - parent = batches.get(parentId); - parentPersistedId = parent.getId(); - } - - BenthosBatch existingBatch = null; - List<BenthosBatch> batchesToBrowse; - if (parent == null) { - batchesToBrowse = benthosBatches.getChildren(); - } else { - batchesToBrowse = parent.getChildBatchs(); - } - - // check if the parent has already a batch with the caracteristic value - // and if the children batch are categorized with the same caracterstic - if (batchesToBrowse != null) { - for (BenthosBatch bb : batchesToBrowse) { - if (bb.getSpecies().equals(species) - && (!bb.getSampleCategoryId().equals(batch.getSampleCategoryId()) - || bb.getSampleCategoryValue().equals(value))) { - - existingBatch = bb; - batches.put(row.getId(), bb); - notImportedBatches.put(row.getId(), batch); - break; - } - } - } - - if (existingBatch == null) { - batch = persistenceService.createBenthosBatch(batch, parentPersistedId); - batches.put(row.getId(), batch); - } - } - - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - return batches; - } - - protected void importBenthosFrequencies(File file, - Map<String, BenthosBatch> batches, - Map<String, BenthosBatch> notImportedBatches, - List<Caracteristic> caracteristics) { - ListMultimap<String, BenthosBatchFrequency> frequencyMap = - ArrayListMultimap.create(); - - Reader reader = TuttiIOUtil.newReader( - new File(file, FREQUENCIES_FILE), - n_("tutti.service.multipost.import.frequencies.error")); - try { - CatchFrequencyRowModel frequencyModel = new CatchFrequencyRowModel(csvSeparator, - caracteristics); - - Import<CatchFrequencyRow> importer = Import.newImport(frequencyModel, reader); - - try { - - for (CatchFrequencyRow frequencyRow : importer) { - if (notImportedBatches.get(frequencyRow.getBatchId()) == null) { - BenthosBatch batch = batches.get(frequencyRow.getBatchId()); - if (batch != null) { - BenthosBatchFrequency frequency = TuttiBeanFactory.newBenthosBatchFrequency(); - frequency.setLengthStepCaracteristic(frequencyRow.getLengthStepCaracteristic()); - frequency.setLengthStep(frequencyRow.getLengthStep()); - frequency.setNumber(frequencyRow.getNumber()); - frequency.setWeight(frequencyRow.getWeight()); - frequency.setBatch(batch); - frequencyMap.put(batch.getId(), frequency); - } - } - } - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - - for (String batchId : frequencyMap.keySet()) { - List<BenthosBatchFrequency> frequencies = frequencyMap.get(batchId); - persistenceService.saveBenthosBatchFrequency(batchId, frequencies); - } - } - - protected void importBenthosWeights(File file, - FishingOperation operation, - CatchWeightsRowModel weightsModel, - Map<String, Object> notImportedData) { - Reader reader = TuttiIOUtil.newReader( - new File(file, WEIGHTS_FILE), - n_("tutti.service.multipost.import.weights.error")); - - try { - Import<CatchWeightsRow> importer = Import.newImport(weightsModel, reader); - - try { - Iterator<CatchWeightsRow> iterator = importer.iterator(); - if (iterator.hasNext()) { - CatchWeightsRow row = iterator.next(); - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operation.getId()); - catchBatch.setFishingOperation(operation); - - if (catchBatch.getBenthosTotalSortedWeight() == null) { - catchBatch.setBenthosTotalSortedWeight(row.getTotalSortedWeight()); - - } else if (row.getTotalSortedWeight() != null) { - notImportedData.put(CatchBatch.PROPERTY_BENTHOS_TOTAL_SORTED_WEIGHT, row.getTotalSortedWeight()); - } - - if (catchBatch.getBenthosTotalInertWeight() == null) { - catchBatch.setBenthosTotalInertWeight(row.getInertWeight()); - - } else if (row.getInertWeight() != null) { - notImportedData.put(CatchBatch.PROPERTY_BENTHOS_TOTAL_INERT_WEIGHT, row.getInertWeight()); - } - - if (catchBatch.getBenthosTotalLivingNotItemizedWeight() == null) { - catchBatch.setBenthosTotalLivingNotItemizedWeight(row.getLivingNotItemizedWeight()); - - } else if (row.getLivingNotItemizedWeight() != null) { - notImportedData.put(CatchBatch.PROPERTY_BENTHOS_TOTAL_LIVING_NOT_ITEMIZED_WEIGHT, - row.getLivingNotItemizedWeight()); - } - - persistenceService.saveCatchBatch(catchBatch); - } - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - } - - //------------------------------------------------------------------------// - //-- Import Marine litter --// - //------------------------------------------------------------------------// - - /** - * Import marine litter batches from a satellite post - * - * @param file the file to import the batches from - * @param operation the operation in which to add the batches - * @return the list of the marine litter which have not been imported, because there were concurrent batches - */ - public Map<String, Object> importMarineLitter(final File file, - final FishingOperation operation) { - - Callable<Map<String, Object>> call = new Callable<Map<String, Object>>() { - - @Override - public Map<String, Object> call() throws Exception { - File tempDir = TuttiIOUtil.explodeZip( - context.getConfig().getTmpDirectory(), - file, - n_("tutti.service.multipost.uncompress.error")); - - //check operation - MarineLitterWeightRowModel weightModel = new MarineLitterWeightRowModel(csvSeparator); - checkSameOperation(tempDir, weightModel, operation); - - String operationId = operation.getId(); - - Map<String, Object> notImportedData = Maps.newHashMap(); - final Map<String, MarineLitterBatch> notImportedBatches = Maps.newLinkedHashMap(); - - BatchContainer<MarineLitterBatch> marineLitterBatches = - persistenceService.getRootMarineLitterBatch(operationId); - List<CaracteristicQualitativeValue> categoryValues = - persistenceService.getMarineLitterCategoryCaracteristic().getQualitativeValue(); - List<CaracteristicQualitativeValue> sizeCategoryValues = - persistenceService.getMarineLitterSizeCategoryCaracteristic().getQualitativeValue(); - - // Import batches - // map containing the batches by their persistence id - final Map<String, MarineLitterBatch> batches = importMarineLitterBatches( - tempDir, - operation, - categoryValues, - sizeCategoryValues, - marineLitterBatches, - notImportedBatches); - - // Import attachments - - importAttachments(tempDir, - batches, - notImportedBatches, - AttachementObjectTypeEnum.BATCH); - - // Import weights - - importMarineLitterCatchWeights(tempDir, - operation, - weightModel, - notImportedData); - - notImportedData.put(BATCHES_KEY, notImportedBatches.values()); - return notImportedData; - - } - }; - Map<String, Object> result = persistenceService.invoke(call); - return result; - } - - protected Map<String, MarineLitterBatch> importMarineLitterBatches(File file, FishingOperation operation, - List<CaracteristicQualitativeValue> categoryValues, - List<CaracteristicQualitativeValue> sizeCategoryValues, - BatchContainer<MarineLitterBatch> marineLitterBatches, - Map<String, MarineLitterBatch> notImportedBatches) { - - Map<String, MarineLitterBatch> batches = Maps.newLinkedHashMap(); - - Reader reader = TuttiIOUtil.newReader( - new File(file, MARINE_LITTER_FILE), - n_("tutti.service.multipost.import.batches.error")); - - try { - - MarineLitterRowModel csvModel = new MarineLitterRowModel(csvSeparator, - categoryValues, - sizeCategoryValues); - - Import<MarineLitterRow> importer = Import.newImport(csvModel, reader); - - try { - for (MarineLitterRow row : importer) { - - // create batch - MarineLitterBatch batch = TuttiBeanFactory.newMarineLitterBatch(); - batch.setFishingOperation(operation); - - batch.setWeight(row.getWeight()); - batch.setNumber(row.getNumber()); - batch.setComment(row.getComment()); - batch.setMarineLitterCategory(row.getCategory()); - batch.setMarineLitterSizeCategory(row.getSizeCategory()); - - MarineLitterBatch existingBatch = null; - List<MarineLitterBatch> batchesToBrowse = marineLitterBatches.getChildren(); - - // check if the parent has already a batch with the caracteristic value - // and if the children batch are categorized with the same caracterstic - if (batchesToBrowse != null) { - for (MarineLitterBatch mlb : batchesToBrowse) { - if (mlb.getMarineLitterCategory().equals(batch.getMarineLitterCategory()) - && mlb.getMarineLitterSizeCategory().equals(batch.getMarineLitterSizeCategory())) { - - existingBatch = mlb; - batches.put(row.getBatchId(), mlb); - notImportedBatches.put(row.getBatchId(), batch); - break; - } - } - } - - if (existingBatch == null) { - batch = persistenceService.createMarineLitterBatch(batch); - batches.put(row.getBatchId(), batch); - } - - } - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - return batches; - } - - protected void importMarineLitterCatchWeights(File file, - FishingOperation operation, - MarineLitterWeightRowModel weightModel, - Map<String, Object> notImportedData) { - - Reader reader = TuttiIOUtil.newReader( - new File(file, WEIGHTS_FILE), - n_("tutti.service.multipost.import.weights.error")); - - Import<MarineLitterWeightRow> weight = Import.newImport(weightModel, reader); - - Iterator<MarineLitterWeightRow> iterator = weight.iterator(); - if (iterator.hasNext()) { - MarineLitterWeightRow row = iterator.next(); - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operation.getId()); - catchBatch.setFishingOperation(operation); - - if (catchBatch.getMarineLitterTotalWeight() == null) { - catchBatch.setMarineLitterTotalWeight(row.getTotalWeight()); - - } else if (row.getTotalWeight() != null) { - notImportedData.put(CatchBatch.PROPERTY_MARINE_LITTER_TOTAL_WEIGHT, row.getTotalWeight()); - } - - persistenceService.saveCatchBatch(catchBatch); - } - } - - //------------------------------------------------------------------------// - //-- Import individual observations --// - //------------------------------------------------------------------------// - - /** - * Import individual observation batches from a satellite post - * - * @param file the file to import the batches from - * @param operation the operation in which to add the batches - */ - public void importIndividualObservation(final File file, - final FishingOperation operation) { - - Callable<Void> call = new Callable<Void>() { - - @Override - public Void call() throws Exception { - File tempDir = TuttiIOUtil.explodeZip( - context.getConfig().getTmpDirectory(), - file, - n_("tutti.service.multipost.uncompress.error")); - - //check operation - FishingOperationRowModel operationModel = - new FishingOperationRowModel(csvSeparator); - checkSameOperation(tempDir, operationModel, operation); - - TuttiDataContext dataContext = context.getDataContext(); - List<Species> speciesList = dataContext.getReferentSpecies(); - List<Caracteristic> caracteristics = dataContext.getCaracteristicWithProtected(); - - // Import batches - // map containing the batches by their persistence id - final Map<String, IndividualObservationBatch> batches = importIndividualObservationBatches( - tempDir, - operation, - speciesList, - caracteristics); - - // Import caracteristics - - importIndividualObservationCaracteristics(file, batches, caracteristics); - - // Persist batches - - for (IndividualObservationBatch batch : batches.values()) { - persistenceService.createIndividualObservationBatch(batch); - } - - // Import attachments - - importAttachments(tempDir, batches, AttachementObjectTypeEnum.SAMPLE); - return null; - } - }; - persistenceService.invoke(call); - } - - protected Map<String, IndividualObservationBatch> importIndividualObservationBatches(File file, FishingOperation operation, - List<Species> speciesList, - List<Caracteristic> caracteristics) { - - Map<String, IndividualObservationBatch> batches = Maps.newLinkedHashMap(); - - - IndividualObservationRowModel csvModel = new IndividualObservationRowModel(csvSeparator, - speciesList, - caracteristics); - Reader reader = TuttiIOUtil.newReader( - new File(file, INDIVIDUAL_OBSERVATION_FILE), - n_("tutti.service.multipost.import.batches.error")); - - try { - Import<IndividualObservationRow> importer = Import.newImport(csvModel, reader); - - try { - for (IndividualObservationRow row : importer) { - - // create batch - IndividualObservationBatch batch = - TuttiBeanFactory.newIndividualObservationBatch(); - batch.setFishingOperation(operation); - - batch.setSpecies(row.getSpecies()); - batch.setWeight(row.getWeight()); - batch.setSize(row.getSize()); - batch.setLengthStepCaracteristic(row.getLengthStepCaracteristic()); -// batch.setSamplingCode(row.getSamplingCode()); -// batch.setCalcifiedPieceSamplingCode(row.getCalcifiedPieceSamplingCode()); - batch.setComment(row.getComment()); - batch.setCaracteristics(new CaracteristicMap()); - - batches.put(row.getBatchId(), batch); - } - - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - return batches; - } - - protected void importIndividualObservationCaracteristics(File file, Map<String, IndividualObservationBatch> batches, - List<Caracteristic> caracteristics) { - - CaracteristicRowModel caracteristicModel = new CaracteristicRowModel(csvSeparator, - caracteristics); - - Reader reader = TuttiIOUtil.newReader( - new File(file, CARACTERISTIC_FILE), - n_("tutti.service.multipost.import.caracteristics.error")); - - try { - Import<CaracteristicRow> importer = Import.newImport(caracteristicModel, reader); - - try { - for (CaracteristicRow caracteristicRow : importer) { - IndividualObservationBatch batch = batches.get(caracteristicRow.getBatchId()); - if (batch != null) { - Caracteristic caracteristic = caracteristicRow.getCaracteristic(); - Serializable value = caracteristicRow.getValue(); - - switch (caracteristic.getCaracteristicType()) { - case QUALITATIVE: - value = TuttiEntities.getQualitativeValue(caracteristic, Integer.parseInt(value.toString())); - break; - - case NUMBER: - value = Float.parseFloat(value.toString()); - break; - } - CaracteristicMap map = batch.getCaracteristics(); - map.put(caracteristic, value); - } - } - - TuttiIOUtil.close(importer, "Could not close importer"); - - } finally { - IOUtils.closeQuietly(importer); - } - - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - } - - //------------------------------------------------------------------------// - //-- Import Accidental catches --// - //------------------------------------------------------------------------// - - /** - * Import accidental catches batches from a satellite post - * - * @param file the file to import the batches from - * @param operation the operation in which to add the batches - */ - public void importAccidentalCatches(final File file, final FishingOperation operation) { - - Callable<Void> call = new Callable<Void>() { - - @Override - public Void call() throws Exception { - File tempDir = TuttiIOUtil.explodeZip( - context.getConfig().getTmpDirectory(), - file, - n_("tutti.service.multipost.uncompress.error")); - - //check operation - FishingOperationRowModel operationModel = - new FishingOperationRowModel(csvSeparator); - checkSameOperation(tempDir, operationModel, operation); - - TuttiDataContext dataContext = context.getDataContext(); - List<Species> speciesList = dataContext.getReferentSpecies(); - List<CaracteristicQualitativeValue> genderValues = dataContext.getGenderValues(); - List<Caracteristic> caracteristics = dataContext.getCaracteristicWithProtected(); - List<CaracteristicQualitativeValue> dedOrAliveValues = dataContext.getDeadOrAliveValues(); - - // Import batches - // map containing the batches by their persistence id - final Map<String, AccidentalBatch> batches = importAccidentalCatchesBatches( - tempDir, - operation, - speciesList, - genderValues, - caracteristics, - dedOrAliveValues - ); - - // Import caracteristics - - importAccidentalCatchesCaracteristics(file, batches, caracteristics); - - // Persist batches - - for (AccidentalBatch batch : batches.values()) { - persistenceService.createAccidentalBatch(batch); - } - - // Import attachments - - importAttachments(tempDir, batches, AttachementObjectTypeEnum.SAMPLE); - return null; - } - }; - persistenceService.invoke(call); - } - - protected Map<String, AccidentalBatch> importAccidentalCatchesBatches(File file, FishingOperation operation, - List<Species> speciesList, - List<CaracteristicQualitativeValue> genderValues, - List<Caracteristic> caracteristics, - List<CaracteristicQualitativeValue> dedOrAliveValues) { - - Map<String, AccidentalBatch> batches = Maps.newLinkedHashMap(); - - Reader reader = TuttiIOUtil.newReader( - new File(file, INDIVIDUAL_OBSERVATION_FILE), - n_("tutti.service.multipost.import.batches.error")); - - try { - - AccidentalCatchRowModel csvModel = new AccidentalCatchRowModel(csvSeparator, - speciesList, - genderValues, - caracteristics, - dedOrAliveValues); - - Import<AccidentalCatchRow> importer = Import.newImport(csvModel, reader); - - try { - for (AccidentalCatchRow row : importer) { - - // create batch - AccidentalBatch batch = TuttiBeanFactory.newAccidentalBatch(); - batch.setFishingOperation(operation); - - batch.setSpecies(row.getSpecies()); - batch.setGender(row.getGender()); - batch.setWeight(row.getWeight()); - batch.setSize(row.getSize()); - batch.setLengthStepCaracteristic(row.getLengthStepCaracteristic()); - batch.setDeadOrAlive(row.getDeadOrAlive()); - batch.setComment(row.getComment()); - batch.setCaracteristics(new CaracteristicMap()); - - batches.put(row.getBatchId(), batch); - } - - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - return batches; - } - - protected void importAccidentalCatchesCaracteristics(File file, Map<String, AccidentalBatch> batches, - List<Caracteristic> caracteristics) { - - CaracteristicRowModel caracteristicModel = new CaracteristicRowModel(csvSeparator, - caracteristics); - - Reader reader = TuttiIOUtil.newReader( - new File(file, CARACTERISTIC_FILE), - n_("tutti.service.multipost.import.caracteristics.error")); - - try { - Import<CaracteristicRow> importer = Import.newImport(caracteristicModel, reader); - - try { - for (CaracteristicRow caracteristicRow : importer) { - AccidentalBatch batch = batches.get(caracteristicRow.getBatchId()); - if (batch != null) { - Caracteristic caracteristic = caracteristicRow.getCaracteristic(); - Serializable value = caracteristicRow.getValue(); - - switch (caracteristic.getCaracteristicType()) { - case QUALITATIVE: - value = TuttiEntities.getQualitativeValue(caracteristic, Integer.parseInt(value.toString())); - break; - - case NUMBER: - value = Float.parseFloat(value.toString()); - break; - } - CaracteristicMap map = batch.getCaracteristics(); - map.put(caracteristic, value); - } - } - - TuttiIOUtil.close(importer, "Could not close importer"); - - } finally { - IOUtils.closeQuietly(importer); - } - - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - - } - - //------------------------------------------------------------------------// - //-- Internal methods --// - //------------------------------------------------------------------------// - - protected Pair<Integer, Serializable> getValueAndCategoryType(CatchRow row) { - - Serializable value = row.getCategoryValue(); - Integer categoryId = row.getCategoryId(); - - SampleCategoryModelEntry categoryModelEntry = - sampleCategoryModel.getCategoryById(categoryId); - - Caracteristic caracteristic = categoryModelEntry.getCaracteristic(); - if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { - CaracteristicQualitativeValue caracteristicQualitativeValue = sampleCategoryValueMap.get(String.valueOf(value)); - Preconditions.checkNotNull(caracteristicQualitativeValue, "Can't find caracteristic qualitative value with id: " + value + " for caracteristic of id: " + categoryId); - value = caracteristicQualitativeValue; - } - return Pair.of(categoryId, value); - } - - protected void checkSameOperation(File directory, - AbstractFishingOperationRowModel fishingOperationRowModel, - FishingOperation operation) { - Reader reader = TuttiIOUtil.newReader( - new File(directory, WEIGHTS_FILE), - n_("tutti.service.multipost.import.operation.error")); - - try { - Import<AbstractFishingOperationRow> importer = Import.<AbstractFishingOperationRow>newImport(fishingOperationRowModel, reader); - - Iterator<AbstractFishingOperationRow> iterator = importer.iterator(); - try { - if (iterator.hasNext()) { - AbstractFishingOperationRow row = iterator.next(); - if (ObjectUtils.notEqual(row.getStationNumber(), operation.getStationNumber()) - || ObjectUtils.notEqual(row.getOperationNumber(), operation.getFishingOperationNumber()) - || ObjectUtils.notEqual(row.getMultirigAggregation(), operation.getMultirigAggregation()) - || ObjectUtils.notEqual(row.getDate(), operation.getGearShootingStartDate())) { - - throw new TuttiBusinessException(_("tutti.service.multipost.import.wrongOperation.error", - decoratorService.getDecoratorByType(FishingOperation.class) - .toString(operation))); - } - } - } finally { - IOUtils.closeQuietly(importer); - } - } finally { - IOUtils.closeQuietly(reader); - } - } - - protected <R extends TuttiEntity> void importAttachments(File directory, - final Map<String, R> data, - final Map<String, R> notImportedData, - AttachementObjectTypeEnum objectType) { - - Function<AttachmentRow, Integer> getObjetcIdFunction = new Function<AttachmentRow, Integer>() { - @Override - public Integer apply(AttachmentRow input) { - Integer result = null; - if (notImportedData.get(input.getBatchId()) == null) { - R batch = data.get(input.getBatchId()); - if (batch != null) { - result = batch.getIdAsInt(); - } - } - return result; - } - }; - - Reader reader = TuttiIOUtil.newReader( - new File(directory, ATTACHMENTS_FILE), - n_("tutti.service.multipost.import.attachments.error")); - - try { - AttachmentRowModel attachmentModel = - new AttachmentRowModel(csvSeparator, new File(directory, ATTACHMENTS_DIRECTORY)); - Import<AttachmentRow> importer = Import.newImport(attachmentModel, reader); - - try { - for (AttachmentRow row : importer) { - Integer objectId = getObjetcIdFunction.apply(row); - if (objectId != null) { - Attachment attachment = TuttiBeanFactory.newAttachment(); - attachment.setName(row.getName()); - attachment.setComment(row.getComment()); - attachment.setObjectType(objectType); - - attachment.setObjectId(objectId); - - persistenceService.createAttachment(attachment, row.getFile()); - } - } - - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - } - - protected <R extends TuttiEntity> void importAttachments(File directory, - final Map<String, R> data, - AttachementObjectTypeEnum objectType) { - - Function<AttachmentRow, Integer> getObjetcIdFunction = new Function<AttachmentRow, Integer>() { - @Override - public Integer apply(AttachmentRow input) { - Integer result = null; - R batch = data.get(input.getBatchId()); - if (batch != null) { - result = batch.getIdAsInt(); - } - return result; - } - }; - - Reader reader = TuttiIOUtil.newReader( - new File(directory, ATTACHMENTS_FILE), - n_("tutti.service.multipost.import.attachments.error")); - - try { - AttachmentRowModel attachmentModel = - new AttachmentRowModel(csvSeparator, new File(directory, ATTACHMENTS_DIRECTORY)); - Import<AttachmentRow> importer = Import.newImport(attachmentModel, reader); - - try { - for (AttachmentRow row : importer) { - Integer objectId = getObjetcIdFunction.apply(row); - if (objectId != null) { - Attachment attachment = TuttiBeanFactory.newAttachment(); - attachment.setName(row.getName()); - attachment.setComment(row.getComment()); - attachment.setObjectType(objectType); - - attachment.setObjectId(objectId); - - persistenceService.createAttachment(attachment, row.getFile()); - } - } - - TuttiIOUtil.close(importer, "Could not close importer"); - } finally { - IOUtils.closeQuietly(importer); - } - - TuttiIOUtil.close(reader, "Could not close reader"); - } finally { - IOUtils.closeQuietly(reader); - } - } - -} Modified: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/config/TuttiServiceConfig.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/config/TuttiServiceConfig.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/config/TuttiServiceConfig.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,6 +26,7 @@ import fr.ifremer.tutti.TuttiIOUtil; import fr.ifremer.tutti.persistence.config.TuttiPersistenceConfig; +import fr.ifremer.tutti.service.WeightUnit; import org.nuiton.util.Version; import org.nuiton.config.ApplicationConfig; @@ -123,6 +124,26 @@ return result.getOptionAsInt(); } + public WeightUnit getSpeciesWeightUnit() { + return applicationConfig.getOption(WeightUnit.class, TuttiServiceConfigOption.WEIGHT_UNIT_SPECIES.getKey()); + } + + public WeightUnit getBenthosWeightUnit() { + return applicationConfig.getOption(WeightUnit.class, TuttiServiceConfigOption.WEIGHT_UNIT_BENTHOS.getKey()); + } + + public WeightUnit getMarineLitterWeightUnit() { + return applicationConfig.getOption(WeightUnit.class, TuttiServiceConfigOption.WEIGHT_UNIT_MARINE_LITTER.getKey()); + } + + public WeightUnit getIndividualObservationWeightUnit() { + return applicationConfig.getOption(WeightUnit.class, TuttiServiceConfigOption.WEIGHT_UNIT_INDIVIDUAL_OBSERVATION.getKey()); + } + + public WeightUnit getAccidentalCatchWeightUnit() { + return applicationConfig.getOption(WeightUnit.class, TuttiServiceConfigOption.WEIGHT_UNIT_ACCIDENTAL_CATCH.getKey()); + } + public void prepareDirectories() { File dataDirectory = getDataDirectory(); Modified: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/config/TuttiServiceConfigOption.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/config/TuttiServiceConfigOption.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/config/TuttiServiceConfigOption.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -24,6 +24,7 @@ * #L% */ +import fr.ifremer.tutti.service.WeightUnit; import org.nuiton.util.Version; import org.nuiton.config.ConfigOptionDef; @@ -107,8 +108,42 @@ "2012", Integer.class, true, - true); + true), + WEIGHT_UNIT_SPECIES( + "tutti.weight.unit.species", + n_("tutti.config.option.weight.unit.species.description"), + WeightUnit.KG.name(), + WeightUnit.class + ), + WEIGHT_UNIT_BENTHOS( + "tutti.weight.unit.benthos", + n_("tutti.config.option.weight.unit.benthos.description"), + WeightUnit.G.name(), + WeightUnit.class + ), + + WEIGHT_UNIT_MARINE_LITTER( + "tutti.weight.unit.marineLitter", + n_("tutti.config.option.weight.unit.marineLitter.description"), + WeightUnit.KG.name(), + WeightUnit.class + ), + + WEIGHT_UNIT_INDIVIDUAL_OBSERVATION( + "tutti.weight.unit.individualObservation", + n_("tutti.config.option.weight.unit.individualObservation.description"), + WeightUnit.G.name(), + WeightUnit.class + ), + + WEIGHT_UNIT_ACCIDENTAL_CATCH( + "tutti.weight.unit.accidentalCatch", + n_("tutti.config.option.weight.unit.accidentalCatch.description"), + WeightUnit.KG.name(), + WeightUnit.class + ); + /** Configuration key. */ private final String key; Modified: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/export/TuttiExportService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/export/TuttiExportService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/export/TuttiExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -43,7 +43,6 @@ import fr.ifremer.tutti.persistence.entities.data.Program; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.Gear; import fr.ifremer.tutti.persistence.entities.referential.Species; @@ -53,7 +52,7 @@ import fr.ifremer.tutti.service.PersistenceService; import fr.ifremer.tutti.service.TuttiCsvUtil; import fr.ifremer.tutti.service.TuttiServiceContext; -import fr.ifremer.tutti.service.catches.TuttiWeightComputingService; +import fr.ifremer.tutti.service.catches.WeightComputingService; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; @@ -89,7 +88,7 @@ protected DecoratorService decoratorService; - protected TuttiWeightComputingService tuttiWeightComputingService; + protected WeightComputingService weightComputingService; protected char csvSeparator; @@ -103,10 +102,6 @@ protected SampleCategoryModel sampleCategoryModel; -// protected Caracteristic sampleIdCaracteristic; -// -// protected Caracteristic otolitheIdCaracteristic; - protected Caracteristic deadOrAliveCaracteristic; protected Caracteristic genderCaracteristic; @@ -120,7 +115,7 @@ super.setServiceContext(context); persistenceService = getService(PersistenceService.class); decoratorService = getService(DecoratorService.class); - tuttiWeightComputingService = getService(TuttiWeightComputingService.class); + weightComputingService = getService(WeightComputingService.class); sampleCategoryModel = context.getSampleCategoryModel(); @@ -128,8 +123,6 @@ verticalOpeningCaracteristic = persistenceService.getVerticalOpeningCaracteristic(); horizontalOpeningWingCaracteristic = persistenceService.getHorizontalOpeningWingCaracteristic(); horizontalOpeningDoorCaracteristic = persistenceService.getHorizontalOpeningDoorCaracteristic(); -// sampleIdCaracteristic = persistenceService.getSampleIdCaracteristic(); -// otolitheIdCaracteristic = persistenceService.getOtolitheIdCaracteristic(); weightMeasuredCaracteristic = persistenceService.getWeightMeasuredCaracteristic(); pmfmIdCaracteristic = persistenceService.getPmfmIdCaracteristic(); deadOrAliveCaracteristic = persistenceService.getDeadOrAliveCaracteristic(); @@ -141,7 +134,6 @@ } public void exportProgram(String programId, - TuttiProtocol protocol, File exportFile, ProgressionModel progressionModel) { Preconditions.checkNotNull(programId); @@ -160,7 +152,7 @@ TuttiIOUtil.forceMkdir(basedir, _("tutti.service.mkDir.error", basedir)); - ExportContext exportContext = createExportContext(basedir, protocol); + ExportContext exportContext = createExportContext(basedir); try { for (Cruise cruise : allCruise) { @@ -181,7 +173,6 @@ } public void exportCruise(String cruiseId, - TuttiProtocol protocol, File exportFile, ProgressionModel progressionModel) { @@ -212,7 +203,7 @@ TuttiIOUtil.forceMkdir(basedir, _("tutti.service.mkDir.error", basedir)); - ExportContext exportContext = createExportContext(basedir, protocol); + ExportContext exportContext = createExportContext(basedir); try { exportCruise(cruise, exportContext, progressionModel); @@ -233,11 +224,10 @@ } } - protected ExportContext createExportContext(File basedir, - TuttiProtocol protocol) { + protected ExportContext createExportContext(File basedir) { - List<Species> allReferentSpecies = persistenceService.getAllReferentSpecies(protocol); + List<Species> allReferentSpecies = persistenceService.getAllReferentSpecies(); Map<String, Species> speciesById = TuttiEntities.splitById(allReferentSpecies); return new ExportContext( @@ -247,15 +237,11 @@ verticalOpeningCaracteristic, horizontalOpeningWingCaracteristic, horizontalOpeningDoorCaracteristic, -// sampleIdCaracteristic, -// otolitheIdCaracteristic, weightMeasuredCaracteristic, deadOrAliveCaracteristic, genderCaracteristic, pmfmIdCaracteristic, sampleCategoryModel, -// samplingOrder, -// samplingToCaracteristic, speciesById); } @@ -268,7 +254,7 @@ // check cruise fishing operations Map<String, String> errors = - tuttiWeightComputingService.checkCruise(cruise.getId()); + weightComputingService.checkCruise(cruise.getId()); progressionModel.increments(1); @@ -852,7 +838,7 @@ public OperationContext(FishingOperation operation, PersistenceService persistenceService, - TuttiWeightComputingService tuttiWeightComputingService) { + WeightComputingService weightComputingService) { this.operation = operation; String operationId = operation.getId(); @@ -873,7 +859,7 @@ boolean withError = false; try { - rootSpeciesBatch = tuttiWeightComputingService.getComputedSpeciesBatches(operation); + rootSpeciesBatch = weightComputingService.getComputedSpeciesBatches(operation); } catch (Exception e) { withError = true; rootSpeciesBatch = @@ -882,7 +868,7 @@ try { rootBenthosBatch = - tuttiWeightComputingService.getComputedBenthosBatches(operation); + weightComputingService.getComputedBenthosBatches(operation); } catch (Exception e) { withError = true; rootBenthosBatch = @@ -891,7 +877,7 @@ try { rootMarineLitterBatch = - tuttiWeightComputingService.getComputedMarineLitterBatches(operation, catchBatch.getMarineLitterTotalWeight()); + weightComputingService.getComputedMarineLitterBatches(operation, catchBatch.getMarineLitterTotalWeight()); } catch (Exception e) { withError = true; rootMarineLitterBatch = @@ -901,7 +887,7 @@ // apply compute weights if (!withError) { - tuttiWeightComputingService.computeCatchBatchWeights( + weightComputingService.computeCatchBatchWeights( catchBatch, rootSpeciesBatch, rootBenthosBatch, @@ -952,7 +938,7 @@ // create it result = new OperationContext(operation, persistenceService, - tuttiWeightComputingService); + weightComputingService); operationContexts.put(operationId, result); } return result; Copied: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/ProtocolImportExportService.java (from rev 1246, trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportService.java) =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/ProtocolImportExportService.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/ProtocolImportExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,525 @@ +package fr.ifremer.tutti.service.protocol; + +/* + * #%L + * Tutti :: Service + * $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.Charsets; +import com.google.common.base.Function; +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Multimap; +import com.google.common.collect.TreeMultimap; +import com.google.common.io.Files; +import fr.ifremer.tutti.TuttiTechnicalException; +import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; +import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; +import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; +import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocols; +import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import fr.ifremer.tutti.persistence.service.TuttiEnumerationFile; +import fr.ifremer.tutti.service.AbstractTuttiService; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.csv.Export; +import org.nuiton.csv.Import; +import org.nuiton.csv.ImportRuntimeException; +import org.nuiton.util.beans.Binder; +import org.nuiton.util.beans.BinderFactory; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import static org.nuiton.i18n.I18n._; + +/** + * To import / export {@link TuttiProtocol} to {@code Yaml} file formats. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +public class ProtocolImportExportService extends AbstractTuttiService { + + /** Logger. */ + private static final Log log = + LogFactory.getLog(ProtocolImportExportService.class); + + protected SampleCategoryModel sampleCategoryModel; + + protected TuttiEnumerationFile enumerationFile; + + @Override + public void setServiceContext(TuttiServiceContext context) { + super.setServiceContext(context); + PersistenceService service = getService(PersistenceService.class); + sampleCategoryModel = context.getDataContext().getSampleCategoryModel(); + enumerationFile = service.getEnumerationFile(); + } + + public void exportProtocol(TuttiProtocol protocol, File file) { + TuttiProtocols.toFile(protocol, file); + } + + public TuttiProtocol importProtocol(File file) { + TuttiProtocol result = TuttiProtocols.fromFile(enumerationFile, file); + return result; + } + + public void importProtocolCaracteristic(File file, + TuttiProtocol protocol, + Map<String, Caracteristic> caracteristicMap) throws IOException { + if (log.isInfoEnabled()) { + log.info("Will import protocol caracteristic from file: " + file); + } + + Multimap<CaracteristicType, String> ids = TreeMultimap.create(); + + CaracteristicRowModel csvModel = + new CaracteristicRowModel(getCsvSeparator(), + caracteristicMap); + + Reader reader = Files.newReader(file, Charsets.UTF_8); + try { + + Import<CaracteristicRow> importer = + Import.newImport(csvModel, reader); + + try { + + for (CaracteristicRow bean : importer) { + + CaracteristicType caracteristicType = bean.getPmfmType(); + Caracteristic caracteristic = bean.getPmfm(); + String id = caracteristic.getId(); + ids.put(caracteristicType, id); + } + importer.close(); + } finally { + IOUtils.closeQuietly(importer); + } + reader.close(); + } catch (Exception e) { + throw new IOException("Could not import protocol [" + protocol.getName() + "] caracteristic from file " + file, e); + } finally { + + IOUtils.closeQuietly(reader); + } + + protocol.setLengthClassesPmfmId( + mergeIds(protocol.getLengthClassesPmfmId(), + ids.get(CaracteristicType.LENGTH_STEP))); + + protocol.setVesselUseFeaturePmfmId( + mergeIds(protocol.getVesselUseFeaturePmfmId(), + ids.get(CaracteristicType.VESSEL_USE_FEATURE))); + + protocol.setGearUseFeaturePmfmId( + mergeIds(protocol.getGearUseFeaturePmfmId(), + ids.get(CaracteristicType.GEAR_USE_FEATURE))); + } + + public void exportAllCaracteristic(File file, + Map<String, Caracteristic> caracteristicMap) { + + if (log.isInfoEnabled()) { + log.info("Will export all caracteristics to file: " + file); + } + + PmfmIdToCaracteristicRowFunction function = + new PmfmIdToCaracteristicRowFunction(caracteristicMap); + + List<CaracteristicRow> rows = Lists.transform( + Lists.newArrayList(caracteristicMap.keySet()), function); + + + CaracteristicRowModel csvModel = + new CaracteristicRowModel(getCsvSeparator(), + caracteristicMap); + + BufferedWriter writer = null; + try { + writer = Files.newWriter(file, Charsets.UTF_8); + Export export = Export.newExport(csvModel, rows); + export.write(writer); + writer.close(); + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.protocol.export.caracteristics.all.error", file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + public void exportProtocolCaracteristic(File file, + TuttiProtocol protocol, + Map<String, Caracteristic> caracteristicMap) { + + if (log.isInfoEnabled()) { + log.info("Will export all caracteristics to file: " + file); + } + + PmfmIdToCaracteristicRowFunction function = + new PmfmIdToCaracteristicRowFunction(caracteristicMap); + + List<CaracteristicRow> rows = Lists.newArrayList(); + + if (!protocol.isLengthClassesPmfmIdEmpty()) { + function.setType(CaracteristicType.LENGTH_STEP); + + rows.addAll(Lists.transform(protocol.getLengthClassesPmfmId(), function)); + } + if (!protocol.isVesselUseFeaturePmfmIdEmpty()) { + function.setType(CaracteristicType.VESSEL_USE_FEATURE); + rows.addAll(Lists.transform(protocol.getVesselUseFeaturePmfmId(), function)); + } + if (!protocol.isGearUseFeaturePmfmIdEmpty()) { + + function.setType(CaracteristicType.GEAR_USE_FEATURE); + rows.addAll(Lists.transform(protocol.getGearUseFeaturePmfmId(), function)); + } + CaracteristicRowModel csvModel = + new CaracteristicRowModel(getCsvSeparator(), + caracteristicMap); + + BufferedWriter writer = null; + try { + writer = Files.newWriter(file, Charsets.UTF_8); + Export export = Export.newExport(csvModel, rows); + export.write(writer); + writer.close(); + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.protocol.export.caracteristics.protocol.error", protocol.getName(), file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + public void importProtocolSpecies(File file, + TuttiProtocol protocol, + Map<String, Caracteristic> caracteristicMap, + Map<String, Species> speciesMap) { + + if (log.isInfoEnabled()) { + log.info("Will import protocol [" + protocol.getName() + + "] species from file: " + file); + } + + Map<Integer, SpeciesProtocol> ids = Maps.newLinkedHashMap(); + + if (!protocol.isSpeciesEmpty()) { + + // get existing species (will be replaced if required) + + for (SpeciesProtocol speciesProtocol : protocol.getSpecies()) { + ids.put(speciesProtocol.getSpeciesReferenceTaxonId(), speciesProtocol); + } + + } + SpeciesRowModel csvModel = new SpeciesRowModel(getCsvSeparator(), + caracteristicMap, + speciesMap); + + Reader reader = null; + try { + reader = Files.newReader(file, Charsets.UTF_8); + + Import<SpeciesRow> importer = Import.newImport(csvModel, reader); + + try { + + Binder<SpeciesRow, SpeciesProtocol> binder = + BinderFactory.newBinder(SpeciesRow.class, + SpeciesProtocol.class); + + for (SpeciesRow bean : importer) { + + Species species = bean.getSpecies(); + Integer id = species.getReferenceTaxonId(); + + SpeciesProtocol sp = ids.get(id); + if (sp == null) { + + // create a new species protocol + sp = TuttiBeanFactory.newSpeciesProtocol(); + } + binder.copy(bean, sp); + sp.setMandatorySampleCategoryId(Lists.newArrayList( + bean.getMandatorySampleCategoryId())); + + ids.put(id, sp); + } + importer.close(); + } finally { + IOUtils.closeQuietly(importer); + } + reader.close(); + + } catch (ImportRuntimeException e) { + String message; + if (e.getCause() != null) { + message = e.getCause().getMessage(); + } else { + message = e.getMessage(); + } + throw new TuttiTechnicalException(message, e); + + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.protocol.import.species.error", protocol.getName(), file), e); + + } finally { + IOUtils.closeQuietly(reader); + } + + List<SpeciesProtocol> values = Lists.newArrayList(ids.values()); + protocol.setSpecies(values); + } + + public void importProtocolBenthos(File file, + TuttiProtocol protocol, + Map<String, Caracteristic> caracteristicMap, + Map<String, Species> speciesMap) { + + if (log.isInfoEnabled()) { + log.info("Will import protocol [" + protocol.getName() + + "] species from file: " + file); + } + + Map<Integer, SpeciesProtocol> ids = Maps.newLinkedHashMap(); + + if (!protocol.isBenthosEmpty()) { + + // get existing species (will be replaced if required) + + for (SpeciesProtocol speciesProtocol : protocol.getBenthos()) { + ids.put(speciesProtocol.getSpeciesReferenceTaxonId(), speciesProtocol); + } + + } + SpeciesRowModel csvModel = new SpeciesRowModel(getCsvSeparator(), + caracteristicMap, + speciesMap); + + Reader reader = null; + try { + reader = Files.newReader(file, Charsets.UTF_8); + + Import<SpeciesRow> importer = Import.newImport(csvModel, reader); + + try { + + Binder<SpeciesRow, SpeciesProtocol> binder = + BinderFactory.newBinder(SpeciesRow.class, + SpeciesProtocol.class); + + for (SpeciesRow bean : importer) { + + Species species = bean.getSpecies(); + Integer id = species.getReferenceTaxonId(); + + SpeciesProtocol sp = ids.get(id); + if (sp == null) { + + // create a new species protocol + sp = TuttiBeanFactory.newSpeciesProtocol(); + } + binder.copy(bean, sp); + + ids.put(id, sp); + } + importer.close(); + } finally { + IOUtils.closeQuietly(importer); + } + reader.close(); + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.protocol.import.benthos.error", protocol.getName(), file), e); + } finally { + IOUtils.closeQuietly(reader); + } + + List<SpeciesProtocol> values = Lists.newArrayList(ids.values()); + protocol.setBenthos(values); + } + + public void exportProtocolSpecies(File file, + List<SpeciesProtocol> protocol, + Map<String, Caracteristic> caracteristicMap, + Map<String, Species> speciesMap) { + if (log.isInfoEnabled()) { + log.info("Will export species to file: " + file); + } + + List<SpeciesRow> rows = Lists.newArrayList(); + + if (CollectionUtils.isNotEmpty(protocol)) { + rows = Lists.transform(protocol, new SpeciesProtocolToSpeciesRowFunction( + caracteristicMap, + speciesMap)); + } + + SpeciesRowModel csvModel = + new SpeciesRowModel(getCsvSeparator(), + caracteristicMap, + speciesMap); + + BufferedWriter writer = null; + try { + writer = Files.newWriter(file, Charsets.UTF_8); + Export export = Export.newExport(csvModel, rows); + export.write(writer); + writer.close(); + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.protocol.export.species.error", file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + public void exportProtocolBenthos(File file, + List<SpeciesProtocol> protocol, + Map<String, Caracteristic> caracteristicMap, + Map<String, Species> speciesMap) { + if (log.isInfoEnabled()) { + log.info("Will export benthos to file: " + file); + } + + List<SpeciesRow> rows = Lists.newArrayList(); + + if (CollectionUtils.isNotEmpty(protocol)) { + rows = Lists.transform(protocol, new SpeciesProtocolToSpeciesRowFunction( + caracteristicMap, + speciesMap)); + } + + SpeciesRowModel csvModel = + new SpeciesRowModel(getCsvSeparator(), + caracteristicMap, + speciesMap); + + BufferedWriter writer = null; + try { + writer = Files.newWriter(file, Charsets.UTF_8); + Export export = Export.newExport(csvModel, rows); + export.write(writer); + writer.close(); + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.protocol.export.benthos.error", file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + protected char getCsvSeparator() { + return context.getConfig().getCsvSeparator(); + } + + protected List<String> mergeIds(Collection<String> fromProtocol, + Collection<String> fromImport) { + List<String> result = Lists.newArrayList(); + + if (CollectionUtils.isNotEmpty(fromProtocol)) { + for (String s : fromProtocol) { + if (!result.contains(s)) { + result.add(s); + } + } + + } + for (String s : fromImport) { + if (!result.contains(s)) { + result.add(s); + } + } + return result; + } + + private static class PmfmIdToCaracteristicRowFunction implements Function<String, CaracteristicRow> { + + private CaracteristicType type; + + private final Map<String, Caracteristic> caracteristicMap; + + public PmfmIdToCaracteristicRowFunction(Map<String, Caracteristic> caracteristicMap) { + this.caracteristicMap = caracteristicMap; + } + + @Override + public CaracteristicRow apply(String input) { + Caracteristic caracteristic = caracteristicMap.get(input); + Preconditions.checkNotNull(caracteristic, "Could not find a caracteristic with id: " + input); + CaracteristicRow result = new CaracteristicRow(); + result.setPmfm(caracteristic); + result.setPmfmType(type); + return result; + } + + public void setType(CaracteristicType type) { + this.type = type; + } + } + + private static class SpeciesProtocolToSpeciesRowFunction implements Function<SpeciesProtocol, SpeciesRow> { + + private final Map<String, Species> speciesMap; + + private final Map<String, Caracteristic> caracteristicMap; + + private final Binder<SpeciesProtocol, SpeciesRow> binder; + + public SpeciesProtocolToSpeciesRowFunction(Map<String, Caracteristic> caracteristicMap, + Map<String, Species> speciesMap) { + this.speciesMap = speciesMap; + this.caracteristicMap = caracteristicMap; + this.binder = BinderFactory.newBinder(SpeciesProtocol.class, + SpeciesRow.class); + } + + @Override + public SpeciesRow apply(SpeciesProtocol input) { + Species species = speciesMap.get(String.valueOf(input.getSpeciesReferenceTaxonId())); + Preconditions.checkNotNull(species, "Could not find a species with id: " + input); + SpeciesRow result = new SpeciesRow(); + binder.copy(input, result); + String pmfmId = input.getLengthStepPmfmId(); + if (pmfmId != null) { + Caracteristic caracteristic = caracteristicMap.get(pmfmId); + result.setLengthStepPmfm(caracteristic); + } + result.setSpecies(species); + // always use a copy of list + result.setMandatorySampleCategoryId(Lists.newArrayList(input.getMandatorySampleCategoryId())); + return result; + } + } +} Deleted: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,525 +0,0 @@ -package fr.ifremer.tutti.service.protocol; - -/* - * #%L - * Tutti :: Service - * $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.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.TreeMultimap; -import com.google.common.io.Files; -import fr.ifremer.tutti.TuttiTechnicalException; -import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; -import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; -import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocols; -import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; -import fr.ifremer.tutti.persistence.entities.referential.Species; -import fr.ifremer.tutti.persistence.service.TuttiEnumerationFile; -import fr.ifremer.tutti.service.AbstractTuttiService; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.csv.Export; -import org.nuiton.csv.Import; -import org.nuiton.csv.ImportRuntimeException; -import org.nuiton.util.beans.Binder; -import org.nuiton.util.beans.BinderFactory; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import static org.nuiton.i18n.I18n._; - -/** - * To import / export {@link TuttiProtocol} to {@code Yaml} file formats. - * - * @author tchemit <chemit@codelutin.com> - * @since 1.0 - */ -public class TuttiProtocolImportExportService extends AbstractTuttiService { - - /** Logger. */ - private static final Log log = - LogFactory.getLog(TuttiProtocolImportExportService.class); - - protected SampleCategoryModel sampleCategoryModel; - - protected TuttiEnumerationFile enumerationFile; - - @Override - public void setServiceContext(TuttiServiceContext context) { - super.setServiceContext(context); - PersistenceService service = getService(PersistenceService.class); - sampleCategoryModel = context.getDataContext().getSampleCategoryModel(); - enumerationFile = service.getEnumerationFile(); - } - - public void exportProtocol(TuttiProtocol protocol, File file) { - TuttiProtocols.toFile(protocol, file); - } - - public TuttiProtocol importProtocol(File file) { - TuttiProtocol result = TuttiProtocols.fromFile(enumerationFile, file); - return result; - } - - public void importProtocolCaracteristic(File file, - TuttiProtocol protocol, - Map<String, Caracteristic> caracteristicMap) throws IOException { - if (log.isInfoEnabled()) { - log.info("Will import protocol caracteristic from file: " + file); - } - - Multimap<CaracteristicType, String> ids = TreeMultimap.create(); - - CaracteristicRowModel csvModel = - new CaracteristicRowModel(getCsvSeparator(), - caracteristicMap); - - Reader reader = Files.newReader(file, Charsets.UTF_8); - try { - - Import<CaracteristicRow> importer = - Import.newImport(csvModel, reader); - - try { - - for (CaracteristicRow bean : importer) { - - CaracteristicType caracteristicType = bean.getPmfmType(); - Caracteristic caracteristic = bean.getPmfm(); - String id = caracteristic.getId(); - ids.put(caracteristicType, id); - } - importer.close(); - } finally { - IOUtils.closeQuietly(importer); - } - reader.close(); - } catch (Exception e) { - throw new IOException("Could not import protocol [" + protocol.getName() + "] caracteristic from file " + file, e); - } finally { - - IOUtils.closeQuietly(reader); - } - - protocol.setLengthClassesPmfmId( - mergeIds(protocol.getLengthClassesPmfmId(), - ids.get(CaracteristicType.LENGTH_STEP))); - - protocol.setVesselUseFeaturePmfmId( - mergeIds(protocol.getVesselUseFeaturePmfmId(), - ids.get(CaracteristicType.VESSEL_USE_FEATURE))); - - protocol.setGearUseFeaturePmfmId( - mergeIds(protocol.getGearUseFeaturePmfmId(), - ids.get(CaracteristicType.GEAR_USE_FEATURE))); - } - - public void exportAllCaracteristic(File file, - Map<String, Caracteristic> caracteristicMap) { - - if (log.isInfoEnabled()) { - log.info("Will export all caracteristics to file: " + file); - } - - PmfmIdToCaracteristicRowFunction function = - new PmfmIdToCaracteristicRowFunction(caracteristicMap); - - List<CaracteristicRow> rows = Lists.transform( - Lists.newArrayList(caracteristicMap.keySet()), function); - - - CaracteristicRowModel csvModel = - new CaracteristicRowModel(getCsvSeparator(), - caracteristicMap); - - BufferedWriter writer = null; - try { - writer = Files.newWriter(file, Charsets.UTF_8); - Export export = Export.newExport(csvModel, rows); - export.write(writer); - writer.close(); - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.protocol.export.caracteristics.all.error", file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - public void exportProtocolCaracteristic(File file, - TuttiProtocol protocol, - Map<String, Caracteristic> caracteristicMap) { - - if (log.isInfoEnabled()) { - log.info("Will export all caracteristics to file: " + file); - } - - PmfmIdToCaracteristicRowFunction function = - new PmfmIdToCaracteristicRowFunction(caracteristicMap); - - List<CaracteristicRow> rows = Lists.newArrayList(); - - if (!protocol.isLengthClassesPmfmIdEmpty()) { - function.setType(CaracteristicType.LENGTH_STEP); - - rows.addAll(Lists.transform(protocol.getLengthClassesPmfmId(), function)); - } - if (!protocol.isVesselUseFeaturePmfmIdEmpty()) { - function.setType(CaracteristicType.VESSEL_USE_FEATURE); - rows.addAll(Lists.transform(protocol.getVesselUseFeaturePmfmId(), function)); - } - if (!protocol.isGearUseFeaturePmfmIdEmpty()) { - - function.setType(CaracteristicType.GEAR_USE_FEATURE); - rows.addAll(Lists.transform(protocol.getGearUseFeaturePmfmId(), function)); - } - CaracteristicRowModel csvModel = - new CaracteristicRowModel(getCsvSeparator(), - caracteristicMap); - - BufferedWriter writer = null; - try { - writer = Files.newWriter(file, Charsets.UTF_8); - Export export = Export.newExport(csvModel, rows); - export.write(writer); - writer.close(); - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.protocol.export.caracteristics.protocol.error", protocol.getName(), file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - public void importProtocolSpecies(File file, - TuttiProtocol protocol, - Map<String, Caracteristic> caracteristicMap, - Map<String, Species> speciesMap) { - - if (log.isInfoEnabled()) { - log.info("Will import protocol [" + protocol.getName() + - "] species from file: " + file); - } - - Map<Integer, SpeciesProtocol> ids = Maps.newLinkedHashMap(); - - if (!protocol.isSpeciesEmpty()) { - - // get existing species (will be replaced if required) - - for (SpeciesProtocol speciesProtocol : protocol.getSpecies()) { - ids.put(speciesProtocol.getSpeciesReferenceTaxonId(), speciesProtocol); - } - - } - SpeciesRowModel csvModel = new SpeciesRowModel(getCsvSeparator(), - caracteristicMap, - speciesMap); - - Reader reader = null; - try { - reader = Files.newReader(file, Charsets.UTF_8); - - Import<SpeciesRow> importer = Import.newImport(csvModel, reader); - - try { - - Binder<SpeciesRow, SpeciesProtocol> binder = - BinderFactory.newBinder(SpeciesRow.class, - SpeciesProtocol.class); - - for (SpeciesRow bean : importer) { - - Species species = bean.getSpecies(); - Integer id = species.getReferenceTaxonId(); - - SpeciesProtocol sp = ids.get(id); - if (sp == null) { - - // create a new species protocol - sp = TuttiBeanFactory.newSpeciesProtocol(); - } - binder.copy(bean, sp); - sp.setMandatorySampleCategoryId(Lists.newArrayList( - bean.getMandatorySampleCategoryId())); - - ids.put(id, sp); - } - importer.close(); - } finally { - IOUtils.closeQuietly(importer); - } - reader.close(); - - } catch (ImportRuntimeException e) { - String message; - if (e.getCause() != null) { - message = e.getCause().getMessage(); - } else { - message = e.getMessage(); - } - throw new TuttiTechnicalException(message, e); - - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.protocol.import.species.error", protocol.getName(), file), e); - - } finally { - IOUtils.closeQuietly(reader); - } - - List<SpeciesProtocol> values = Lists.newArrayList(ids.values()); - protocol.setSpecies(values); - } - - public void importProtocolBenthos(File file, - TuttiProtocol protocol, - Map<String, Caracteristic> caracteristicMap, - Map<String, Species> speciesMap) { - - if (log.isInfoEnabled()) { - log.info("Will import protocol [" + protocol.getName() + - "] species from file: " + file); - } - - Map<Integer, SpeciesProtocol> ids = Maps.newLinkedHashMap(); - - if (!protocol.isBenthosEmpty()) { - - // get existing species (will be replaced if required) - - for (SpeciesProtocol speciesProtocol : protocol.getBenthos()) { - ids.put(speciesProtocol.getSpeciesReferenceTaxonId(), speciesProtocol); - } - - } - SpeciesRowModel csvModel = new SpeciesRowModel(getCsvSeparator(), - caracteristicMap, - speciesMap); - - Reader reader = null; - try { - reader = Files.newReader(file, Charsets.UTF_8); - - Import<SpeciesRow> importer = Import.newImport(csvModel, reader); - - try { - - Binder<SpeciesRow, SpeciesProtocol> binder = - BinderFactory.newBinder(SpeciesRow.class, - SpeciesProtocol.class); - - for (SpeciesRow bean : importer) { - - Species species = bean.getSpecies(); - Integer id = species.getReferenceTaxonId(); - - SpeciesProtocol sp = ids.get(id); - if (sp == null) { - - // create a new species protocol - sp = TuttiBeanFactory.newSpeciesProtocol(); - } - binder.copy(bean, sp); - - ids.put(id, sp); - } - importer.close(); - } finally { - IOUtils.closeQuietly(importer); - } - reader.close(); - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.protocol.import.benthos.error", protocol.getName(), file), e); - } finally { - IOUtils.closeQuietly(reader); - } - - List<SpeciesProtocol> values = Lists.newArrayList(ids.values()); - protocol.setBenthos(values); - } - - public void exportProtocolSpecies(File file, - List<SpeciesProtocol> protocol, - Map<String, Caracteristic> caracteristicMap, - Map<String, Species> speciesMap) { - if (log.isInfoEnabled()) { - log.info("Will export species to file: " + file); - } - - List<SpeciesRow> rows = Lists.newArrayList(); - - if (CollectionUtils.isNotEmpty(protocol)) { - rows = Lists.transform(protocol, new SpeciesProtocolToSpeciesRowFunction( - caracteristicMap, - speciesMap)); - } - - SpeciesRowModel csvModel = - new SpeciesRowModel(getCsvSeparator(), - caracteristicMap, - speciesMap); - - BufferedWriter writer = null; - try { - writer = Files.newWriter(file, Charsets.UTF_8); - Export export = Export.newExport(csvModel, rows); - export.write(writer); - writer.close(); - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.protocol.export.species.error", file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - public void exportProtocolBenthos(File file, - List<SpeciesProtocol> protocol, - Map<String, Caracteristic> caracteristicMap, - Map<String, Species> speciesMap) { - if (log.isInfoEnabled()) { - log.info("Will export benthos to file: " + file); - } - - List<SpeciesRow> rows = Lists.newArrayList(); - - if (CollectionUtils.isNotEmpty(protocol)) { - rows = Lists.transform(protocol, new SpeciesProtocolToSpeciesRowFunction( - caracteristicMap, - speciesMap)); - } - - SpeciesRowModel csvModel = - new SpeciesRowModel(getCsvSeparator(), - caracteristicMap, - speciesMap); - - BufferedWriter writer = null; - try { - writer = Files.newWriter(file, Charsets.UTF_8); - Export export = Export.newExport(csvModel, rows); - export.write(writer); - writer.close(); - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.protocol.export.benthos.error", file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - protected char getCsvSeparator() { - return context.getConfig().getCsvSeparator(); - } - - protected List<String> mergeIds(Collection<String> fromProtocol, - Collection<String> fromImport) { - List<String> result = Lists.newArrayList(); - - if (CollectionUtils.isNotEmpty(fromProtocol)) { - for (String s : fromProtocol) { - if (!result.contains(s)) { - result.add(s); - } - } - - } - for (String s : fromImport) { - if (!result.contains(s)) { - result.add(s); - } - } - return result; - } - - private static class PmfmIdToCaracteristicRowFunction implements Function<String, CaracteristicRow> { - - private CaracteristicType type; - - private final Map<String, Caracteristic> caracteristicMap; - - public PmfmIdToCaracteristicRowFunction(Map<String, Caracteristic> caracteristicMap) { - this.caracteristicMap = caracteristicMap; - } - - @Override - public CaracteristicRow apply(String input) { - Caracteristic caracteristic = caracteristicMap.get(input); - Preconditions.checkNotNull(caracteristic, "Could not find a caracteristic with id: " + input); - CaracteristicRow result = new CaracteristicRow(); - result.setPmfm(caracteristic); - result.setPmfmType(type); - return result; - } - - public void setType(CaracteristicType type) { - this.type = type; - } - } - - private static class SpeciesProtocolToSpeciesRowFunction implements Function<SpeciesProtocol, SpeciesRow> { - - private final Map<String, Species> speciesMap; - - private final Map<String, Caracteristic> caracteristicMap; - - private final Binder<SpeciesProtocol, SpeciesRow> binder; - - public SpeciesProtocolToSpeciesRowFunction(Map<String, Caracteristic> caracteristicMap, - Map<String, Species> speciesMap) { - this.speciesMap = speciesMap; - this.caracteristicMap = caracteristicMap; - this.binder = BinderFactory.newBinder(SpeciesProtocol.class, - SpeciesRow.class); - } - - @Override - public SpeciesRow apply(SpeciesProtocol input) { - Species species = speciesMap.get(String.valueOf(input.getSpeciesReferenceTaxonId())); - Preconditions.checkNotNull(species, "Could not find a species with id: " + input); - SpeciesRow result = new SpeciesRow(); - binder.copy(input, result); - String pmfmId = input.getLengthStepPmfmId(); - if (pmfmId != null) { - Caracteristic caracteristic = caracteristicMap.get(pmfmId); - result.setLengthStepPmfm(caracteristic); - } - result.setSpecies(species); - // always use a copy of list - result.setMandatorySampleCategoryId(Lists.newArrayList(input.getMandatorySampleCategoryId())); - return result; - } - } -} Copied: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/PupitriImportExportService.java (from rev 1246, trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportService.java) =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/PupitriImportExportService.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/PupitriImportExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,482 @@ +package fr.ifremer.tutti.service.pupitri; + +/* + * #%L + * Tutti :: Service + * $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.Charsets; +import com.google.common.base.Function; +import com.google.common.base.Preconditions; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ListMultimap; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimaps; +import com.google.common.collect.Sets; +import com.google.common.io.Files; +import fr.ifremer.tutti.TuttiTechnicalException; +import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; +import fr.ifremer.tutti.persistence.entities.TuttiEntities; +import fr.ifremer.tutti.persistence.entities.data.AttachementObjectTypeEnum; +import fr.ifremer.tutti.persistence.entities.data.Attachment; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.CatchBatch; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; +import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import fr.ifremer.tutti.persistence.service.TuttiEnumerationFile; +import fr.ifremer.tutti.service.AbstractTuttiService; +import fr.ifremer.tutti.service.DecoratorService; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.TuttiDataContext; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.csv.Export; +import org.nuiton.csv.Import; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.Serializable; +import java.text.DateFormat; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n._; + +/** + * @author kmorin <kmorin@codelutin.com> + * @since 1.2 + */ +public class PupitriImportExportService extends AbstractTuttiService { + + private static final Log log = + LogFactory.getLog(PupitriImportExportService.class); + + protected PersistenceService persistenceService; + + protected TuttiDataContext dataContext; + + protected CaracteristicQualitativeValue sortedCaracteristic; + + protected CaracteristicQualitativeValue unsortedCaracteristic; + + protected CaracteristicQualitativeValue maleCaracteristic; + + protected CaracteristicQualitativeValue femaleCaracteristic; + + protected CaracteristicQualitativeValue smallCaracteristic; + + protected CaracteristicQualitativeValue mediumCaracteristic; + + protected CaracteristicQualitativeValue bigCaracteristic; + + @Override + public void setServiceContext(TuttiServiceContext context) { + super.setServiceContext(context); + persistenceService = getService(PersistenceService.class); + dataContext = context.getDataContext(); + + TuttiEnumerationFile enumerationFile = + persistenceService.getEnumerationFile(); + + { // sorted/unsorted caracteristic + Caracteristic caracteristic = + persistenceService.getSortedUnsortedCaracteristic(); + + sortedCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_VRAC_ID); + unsortedCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_HORS_VRAC_ID); + } + + { // sex category + Caracteristic caracteristic = persistenceService.getSexCaracteristic(); + + maleCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SEX_MALE_ID); + femaleCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SEX_FEMALE_ID); + } + { // size category + Caracteristic caracteristic = persistenceService.getSizeCategoryCaracteristic(); + smallCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SIZE_SMALL_ID); + mediumCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SIZE_MEDIUM_ID); + bigCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SIZE_BIG_ID); + } + } + + /** + * @param trunkFile incoming trunk file + * @param carrouselFile incoming carroussle file + * @param operation target operation + * @param catchBatch target catch batch + * @return the number of rows of the .car file which have not been imported + */ + public int importPupitri(File trunkFile, + File carrouselFile, + FishingOperation operation, + CatchBatch catchBatch) { + + importPupitriTrunk(trunkFile, operation, catchBatch); + + int result = importPupitriCarrousel(carrouselFile, operation, catchBatch); + + addFileAsAttachment(trunkFile, catchBatch); + addFileAsAttachment(carrouselFile, catchBatch); + + persistenceService.saveCatchBatch(catchBatch); + + return result; + } + + protected void addFileAsAttachment(File f, CatchBatch catchBatch) { + Attachment attachment = TuttiBeanFactory.newAttachment(); + attachment.setObjectType(AttachementObjectTypeEnum.CATCH_BATCH); + attachment.setObjectId(Integer.valueOf(catchBatch.getId())); + attachment.setName(f.getName()); + String date = DateFormat.getDateTimeInstance().format(new Date()); + String comment = _("tutti.service.pupitri.import.attachment.comment", date); + attachment.setComment(comment); + persistenceService.createAttachment(attachment, f); + } + + protected void importPupitriTrunk(File file, FishingOperation operation, CatchBatch catchBatch) { + + if (log.isInfoEnabled()) { + log.info("Will import pupitri operation [" + operation.toString() + + "] trunk from file: " + file); + } + + char separator = ','; + TrunkRowModel csvModel = new TrunkRowModel(separator); + + Reader reader = null; + File fileWithHeaders = null; + Import<TrunkRow> importer = null; + + try { + fileWithHeaders = new File(FileUtils.getTempDirectory(), file.getName()); + String headers = TrunkRow.PROPERTY_FILE_ORIGIN + separator + + TrunkRow.PROPERTY_DATE + separator + + TrunkRow.PROPERTY_TIME + separator + + TrunkRow.PROPERTY_BALANCE_ID + separator + + TrunkRow.PROPERTY_SIGN + separator + + TrunkRow.PROPERTY_OPERATION_CODE + separator + + TrunkRow.PROPERTY_RIG_NUMBER + separator + + TrunkRow.PROPERTY_DIRECTION + separator + + TrunkRow.PROPERTY_WEIGHT; + + FileUtils.writeLines(fileWithHeaders, Collections.singletonList(headers)); + log.info(FileUtils.readFileToString(fileWithHeaders)); + FileUtils.writeLines(fileWithHeaders, FileUtils.readLines(file), true); + log.info(FileUtils.readFileToString(fileWithHeaders)); + + reader = Files.newReader(fileWithHeaders, Charsets.UTF_8); + + importer = Import.newImport(csvModel, reader); + + Float sortedWeight = 0f; + Float rejectedWeight = 0f; + String operationNumber = operation.getStationNumber(); + String rigNumber = operation.getMultirigAggregation(); + + for (TrunkRow bean : importer) { + if (bean.getOperationCode().equals(operationNumber) + && bean.getRigNumber().equals(rigNumber)) { + + switch (bean.getDirection()) { + case VAT: + sortedWeight += bean.getWeight(); + break; + + case VNT: + rejectedWeight += bean.getWeight(); + } + } + + } + catchBatch.setCatchTotalSortedTremisWeight(sortedWeight); + catchBatch.setCatchTotalRejectedWeight(rejectedWeight); + + importer.close(); + reader.close(); + + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.pupitri.import.trunk.error", operation.toString(), file), e); + + } finally { + IOUtils.closeQuietly(importer); + IOUtils.closeQuietly(reader); + FileUtils.deleteQuietly(fileWithHeaders); + } + + } + + protected int importPupitriCarrousel(File carrouselFile, + FishingOperation operation, + CatchBatch catchBatch) { + + if (log.isInfoEnabled()) { + log.info("Will import pupitri operation [" + operation.toString() + + "] carrousel from file: " + carrouselFile); + } + + int result = 0; + Reader reader = null; + File fileWithHeaders = null; + + Import<CarrouselRow> carrouselImporter = null; + char carrouselSeparator = ','; + CarrouselRowModel carrouselCsvModel = new CarrouselRowModel(carrouselSeparator); + + try { + + // get the map of species by survey code + ListMultimap<String, Species> speciesBySurveyCode = ArrayListMultimap.create(); + + speciesBySurveyCode.putAll( + Multimaps.index(dataContext.getReferentSpeciesWithSurveyCode(), + new Function<Species, String>() { + @Override + public String apply(Species input) { + String surveyCode = String.valueOf(input.getSurveyCode()); + int end = Math.min(surveyCode.length(), 7); + return surveyCode.substring(0, end); + } + }) + ); + speciesBySurveyCode.putAll(TuttiEntities.splitByRefTaxCode(dataContext.getReferentSpecies())); + + // import the batches + String[] header = new String[]{ + CarrouselRow.PROPERTY_FILE_ORIGIN, + CarrouselRow.PROPERTY_DATE, + CarrouselRow.PROPERTY_TIME, + CarrouselRow.PROPERTY_BALANCE_ID, + CarrouselRow.PROPERTY_TO_CONFIRM, + CarrouselRow.PROPERTY_OPERATION_CODE, + CarrouselRow.PROPERTY_RIG_NUMBER, + CarrouselRow.PROPERTY_BOX_TYPE, + CarrouselRow.PROPERTY_SPECIES_ID, + CarrouselRow.PROPERTY_SIGN, + CarrouselRow.PROPERTY_DIRECTION, + CarrouselRow.PROPERTY_WEIGHT + }; + fileWithHeaders = createFileWithHeaders(carrouselFile, header, carrouselSeparator); + reader = Files.newReader(fileWithHeaders, Charsets.UTF_8); + carrouselImporter = Import.newImport(carrouselCsvModel, reader); + + String operationNumber = operation.getStationNumber(); + String rigNumber = operation.getMultirigAggregation(); + + Float carrouselSortedWeight = 0f; + + List<PupitriCatch> catches = Lists.newArrayList(); + Set<String> notFoundSpecies = Sets.newHashSet(); + + for (CarrouselRow bean : carrouselImporter) { + // is the bean from the current operation and rig ? + if (bean.getOperationCode().equals(operationNumber) + && bean.getRigNumber().equals(rigNumber)) { + + String speciesId = bean.getSpeciesId(); + List<Species> speciesList = speciesBySurveyCode.get(speciesId); + Float beanWeight = bean.getWeight(); + if (beanWeight < 0f) { + beanWeight = 0f; + } + boolean sorted; + switch (bean.getDirection()) { + case HOV: + sorted = false; + break; + + default: + sorted = true; + carrouselSortedWeight += beanWeight; + } + + if (CollectionUtils.isNotEmpty(speciesList)) { + + Species species = speciesList.get(0); + PupitriCatch pupitriCatch = new PupitriCatch(species, sorted); + int catchIndex = catches.indexOf(pupitriCatch); + if (catchIndex >= 0) { + pupitriCatch = catches.get(catchIndex); + } else { + catches.add(pupitriCatch); + } + pupitriCatch.addToSign(bean.getSign(), beanWeight); + + } else { + notFoundSpecies.add(speciesId); + } + } + } + result = notFoundSpecies.size(); + catchBatch.setCatchTotalSortedCarousselWeight(carrouselSortedWeight); + + BatchContainer<SpeciesBatch> rootSpeciesBatch = persistenceService.getRootSpeciesBatch(operation.getId(), null); + for (SpeciesBatch batch : rootSpeciesBatch.getChildren()) { + persistenceService.deleteSpeciesBatch(batch.getId()); + } + + TuttiEnumerationFile enumerationFile = persistenceService.getEnumerationFile(); + + for (PupitriCatch pupitriCatch : catches) { + + Float catchWeight = pupitriCatch.getWeightBySign().get(PupitriCatch.Signs.DEFAULT); + CaracteristicQualitativeValue cqv = pupitriCatch.isSorted() ? + sortedCaracteristic : unsortedCaracteristic; + + Species species = pupitriCatch.getSpecies(); + + SpeciesBatch batch = createSpeciesBatch(operation, + species, + catchWeight, + enumerationFile.PMFM_ID_SORTED_UNSORTED, + cqv); + + batch = persistenceService.createSpeciesBatch(batch, null); + + // if the batch is splitted + if (catchWeight == null) { + Integer categoryId = null; + for (PupitriCatch.Signs s : pupitriCatch.getWeightBySign().keySet()) { + CaracteristicQualitativeValue splitCqv = null; + switch (s) { + case MALE: + categoryId = enumerationFile.PMFM_ID_SEX; + splitCqv = maleCaracteristic; + break; + + case FEMALE: + categoryId = enumerationFile.PMFM_ID_SEX; + splitCqv = femaleCaracteristic; + break; + + case SMALL: + categoryId = enumerationFile.PMFM_ID_SIZE_CATEGORY; + splitCqv = smallCaracteristic; + break; + + case MEDIUM: + categoryId = enumerationFile.PMFM_ID_SIZE_CATEGORY; + splitCqv = mediumCaracteristic; + break; + + case BIG: + categoryId = enumerationFile.PMFM_ID_SIZE_CATEGORY; + splitCqv = bigCaracteristic; + break; + } + + SpeciesBatch childBatch = createSpeciesBatch( + operation, + species, + pupitriCatch.getWeightBySign().get(s), + categoryId, + splitCqv + ); + + persistenceService.createSpeciesBatch(childBatch, batch.getId()); + } + } + } + + carrouselImporter.close(); + reader.close(); + + } catch (Exception e) { + DecoratorService service = getService(DecoratorService.class); + throw new TuttiTechnicalException(_("tutti.service.pupitri.import.carrousel.error", carrouselFile, service.getDecorator(operation).toString(operation)), e);//"Could not import carrousel data [" + operation.toString() + "] from file " + carrouselFile + + } finally { + IOUtils.closeQuietly(carrouselImporter); + IOUtils.closeQuietly(reader); + FileUtils.deleteQuietly(fileWithHeaders); + } + + return result; + } + + + public void exportSpecies(List<Species> species, File target) { + SpeciesRowModel speciesCsvModel = new SpeciesRowModel(';'); + + List<SpeciesRow> rows = Lists.newArrayList(); + + if (CollectionUtils.isNotEmpty(species)) { + rows = Lists.transform(species, new Function<Species, SpeciesRow>() { + + public SpeciesRow apply(Species input) { + Preconditions.checkNotNull(input.getSurveyCode(), + "Unable to export a species with a null survey code : " + input); + SpeciesRow row = new SpeciesRow(); + String codeFirstPart = StringUtils.substring(input.getSurveyCode(), 0, 4); + row.setCodeFirstPart(StringUtils.rightPad(codeFirstPart, 4)); + String codeSecondPart = StringUtils.substring(input.getSurveyCode(), 4, 7); + row.setCodeSecondPart(StringUtils.rightPad(codeSecondPart, 3)); + row.setScientificName(input.getName()); + return row; + } + }); + } + + try { + Export.exportToFile(speciesCsvModel, rows, target, Charsets.UTF_8, false); + + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.pupitri.export.species.error", target), e); + } + } + + protected SpeciesBatch createSpeciesBatch(FishingOperation operation, + Species species, + Float catchWeight, + Integer categoryId, + Serializable cqv) { + SpeciesBatch batch = TuttiBeanFactory.newSpeciesBatch(); + batch.setFishingOperation(operation); + batch.setSampleCategoryId(categoryId); + batch.setSampleCategoryValue(cqv); + batch.setSpecies(species); + batch.setSampleCategoryWeight(catchWeight); + return batch; + } + + protected File createFileWithHeaders(File file, String[] header, char separator) throws IOException { + File fileWithHeaders = new File(FileUtils.getTempDirectory(), file.getName()); + String headers = StringUtils.join(header, separator); + + FileUtils.writeLines(fileWithHeaders, Collections.singletonList(headers)); + FileUtils.writeLines(fileWithHeaders, FileUtils.readLines(file), true); + + return fileWithHeaders; + } +} Deleted: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,482 +0,0 @@ -package fr.ifremer.tutti.service.pupitri; - -/* - * #%L - * Tutti :: Service - * $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.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimaps; -import com.google.common.collect.Sets; -import com.google.common.io.Files; -import fr.ifremer.tutti.TuttiTechnicalException; -import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; -import fr.ifremer.tutti.persistence.entities.TuttiEntities; -import fr.ifremer.tutti.persistence.entities.data.AttachementObjectTypeEnum; -import fr.ifremer.tutti.persistence.entities.data.Attachment; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -import fr.ifremer.tutti.persistence.entities.data.CatchBatch; -import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; -import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; -import fr.ifremer.tutti.persistence.entities.referential.Species; -import fr.ifremer.tutti.persistence.service.TuttiEnumerationFile; -import fr.ifremer.tutti.service.AbstractTuttiService; -import fr.ifremer.tutti.service.DecoratorService; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.TuttiDataContext; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.csv.Export; -import org.nuiton.csv.Import; - -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.Serializable; -import java.text.DateFormat; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n._; - -/** - * @author kmorin <kmorin@codelutin.com> - * @since 1.2 - */ -public class TuttiPupitriImportExportService extends AbstractTuttiService { - - private static final Log log = - LogFactory.getLog(TuttiPupitriImportExportService.class); - - protected PersistenceService persistenceService; - - protected TuttiDataContext dataContext; - - protected CaracteristicQualitativeValue sortedCaracteristic; - - protected CaracteristicQualitativeValue unsortedCaracteristic; - - protected CaracteristicQualitativeValue maleCaracteristic; - - protected CaracteristicQualitativeValue femaleCaracteristic; - - protected CaracteristicQualitativeValue smallCaracteristic; - - protected CaracteristicQualitativeValue mediumCaracteristic; - - protected CaracteristicQualitativeValue bigCaracteristic; - - @Override - public void setServiceContext(TuttiServiceContext context) { - super.setServiceContext(context); - persistenceService = getService(PersistenceService.class); - dataContext = context.getDataContext(); - - TuttiEnumerationFile enumerationFile = - persistenceService.getEnumerationFile(); - - { // sorted/unsorted caracteristic - Caracteristic caracteristic = - persistenceService.getSortedUnsortedCaracteristic(); - - sortedCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_VRAC_ID); - unsortedCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_HORS_VRAC_ID); - } - - { // sex category - Caracteristic caracteristic = persistenceService.getSexCaracteristic(); - - maleCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SEX_MALE_ID); - femaleCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SEX_FEMALE_ID); - } - { // size category - Caracteristic caracteristic = persistenceService.getSizeCategoryCaracteristic(); - smallCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SIZE_SMALL_ID); - mediumCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SIZE_MEDIUM_ID); - bigCaracteristic = TuttiEntities.getQualitativeValue(caracteristic, enumerationFile.QUALITATIVE_SIZE_BIG_ID); - } - } - - /** - * @param trunkFile incoming trunk file - * @param carrouselFile incoming carroussle file - * @param operation target operation - * @param catchBatch target catch batch - * @return the number of rows of the .car file which have not been imported - */ - public int importPupitri(File trunkFile, - File carrouselFile, - FishingOperation operation, - CatchBatch catchBatch) { - - importPupitriTrunk(trunkFile, operation, catchBatch); - - int result = importPupitriCarrousel(carrouselFile, operation, catchBatch); - - addFileAsAttachment(trunkFile, catchBatch); - addFileAsAttachment(carrouselFile, catchBatch); - - persistenceService.saveCatchBatch(catchBatch); - - return result; - } - - protected void addFileAsAttachment(File f, CatchBatch catchBatch) { - Attachment attachment = TuttiBeanFactory.newAttachment(); - attachment.setObjectType(AttachementObjectTypeEnum.CATCH_BATCH); - attachment.setObjectId(Integer.valueOf(catchBatch.getId())); - attachment.setName(f.getName()); - String date = DateFormat.getDateTimeInstance().format(new Date()); - String comment = _("tutti.service.pupitri.import.attachment.comment", date); - attachment.setComment(comment); - persistenceService.createAttachment(attachment, f); - } - - protected void importPupitriTrunk(File file, FishingOperation operation, CatchBatch catchBatch) { - - if (log.isInfoEnabled()) { - log.info("Will import pupitri operation [" + operation.toString() + - "] trunk from file: " + file); - } - - char separator = ','; - TrunkRowModel csvModel = new TrunkRowModel(separator); - - Reader reader = null; - File fileWithHeaders = null; - Import<TrunkRow> importer = null; - - try { - fileWithHeaders = new File(FileUtils.getTempDirectory(), file.getName()); - String headers = TrunkRow.PROPERTY_FILE_ORIGIN + separator + - TrunkRow.PROPERTY_DATE + separator + - TrunkRow.PROPERTY_TIME + separator + - TrunkRow.PROPERTY_BALANCE_ID + separator + - TrunkRow.PROPERTY_SIGN + separator + - TrunkRow.PROPERTY_OPERATION_CODE + separator + - TrunkRow.PROPERTY_RIG_NUMBER + separator + - TrunkRow.PROPERTY_DIRECTION + separator + - TrunkRow.PROPERTY_WEIGHT; - - FileUtils.writeLines(fileWithHeaders, Collections.singletonList(headers)); - log.info(FileUtils.readFileToString(fileWithHeaders)); - FileUtils.writeLines(fileWithHeaders, FileUtils.readLines(file), true); - log.info(FileUtils.readFileToString(fileWithHeaders)); - - reader = Files.newReader(fileWithHeaders, Charsets.UTF_8); - - importer = Import.newImport(csvModel, reader); - - Float sortedWeight = 0f; - Float rejectedWeight = 0f; - String operationNumber = operation.getStationNumber(); - String rigNumber = operation.getMultirigAggregation(); - - for (TrunkRow bean : importer) { - if (bean.getOperationCode().equals(operationNumber) - && bean.getRigNumber().equals(rigNumber)) { - - switch (bean.getDirection()) { - case VAT: - sortedWeight += bean.getWeight(); - break; - - case VNT: - rejectedWeight += bean.getWeight(); - } - } - - } - catchBatch.setCatchTotalSortedTremisWeight(sortedWeight); - catchBatch.setCatchTotalRejectedWeight(rejectedWeight); - - importer.close(); - reader.close(); - - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.pupitri.import.trunk.error", operation.toString(), file), e); - - } finally { - IOUtils.closeQuietly(importer); - IOUtils.closeQuietly(reader); - FileUtils.deleteQuietly(fileWithHeaders); - } - - } - - protected int importPupitriCarrousel(File carrouselFile, - FishingOperation operation, - CatchBatch catchBatch) { - - if (log.isInfoEnabled()) { - log.info("Will import pupitri operation [" + operation.toString() + - "] carrousel from file: " + carrouselFile); - } - - int result = 0; - Reader reader = null; - File fileWithHeaders = null; - - Import<CarrouselRow> carrouselImporter = null; - char carrouselSeparator = ','; - CarrouselRowModel carrouselCsvModel = new CarrouselRowModel(carrouselSeparator); - - try { - - // get the map of species by survey code - ListMultimap<String, Species> speciesBySurveyCode = ArrayListMultimap.create(); - - speciesBySurveyCode.putAll( - Multimaps.index(dataContext.getReferentSpeciesWithSurveyCode(), - new Function<Species, String>() { - @Override - public String apply(Species input) { - String surveyCode = String.valueOf(input.getSurveyCode()); - int end = Math.min(surveyCode.length(), 7); - return surveyCode.substring(0, end); - } - }) - ); - speciesBySurveyCode.putAll(TuttiEntities.splitByRefTaxCode(dataContext.getReferentSpecies())); - - // import the batches - String[] header = new String[]{ - CarrouselRow.PROPERTY_FILE_ORIGIN, - CarrouselRow.PROPERTY_DATE, - CarrouselRow.PROPERTY_TIME, - CarrouselRow.PROPERTY_BALANCE_ID, - CarrouselRow.PROPERTY_TO_CONFIRM, - CarrouselRow.PROPERTY_OPERATION_CODE, - CarrouselRow.PROPERTY_RIG_NUMBER, - CarrouselRow.PROPERTY_BOX_TYPE, - CarrouselRow.PROPERTY_SPECIES_ID, - CarrouselRow.PROPERTY_SIGN, - CarrouselRow.PROPERTY_DIRECTION, - CarrouselRow.PROPERTY_WEIGHT - }; - fileWithHeaders = createFileWithHeaders(carrouselFile, header, carrouselSeparator); - reader = Files.newReader(fileWithHeaders, Charsets.UTF_8); - carrouselImporter = Import.newImport(carrouselCsvModel, reader); - - String operationNumber = operation.getStationNumber(); - String rigNumber = operation.getMultirigAggregation(); - - Float carrouselSortedWeight = 0f; - - List<PupitriCatch> catches = Lists.newArrayList(); - Set<String> notFoundSpecies = Sets.newHashSet(); - - for (CarrouselRow bean : carrouselImporter) { - // is the bean from the current operation and rig ? - if (bean.getOperationCode().equals(operationNumber) - && bean.getRigNumber().equals(rigNumber)) { - - String speciesId = bean.getSpeciesId(); - List<Species> speciesList = speciesBySurveyCode.get(speciesId); - Float beanWeight = bean.getWeight(); - if (beanWeight < 0f) { - beanWeight = 0f; - } - boolean sorted; - switch (bean.getDirection()) { - case HOV: - sorted = false; - break; - - default: - sorted = true; - carrouselSortedWeight += beanWeight; - } - - if (CollectionUtils.isNotEmpty(speciesList)) { - - Species species = speciesList.get(0); - PupitriCatch pupitriCatch = new PupitriCatch(species, sorted); - int catchIndex = catches.indexOf(pupitriCatch); - if (catchIndex >= 0) { - pupitriCatch = catches.get(catchIndex); - } else { - catches.add(pupitriCatch); - } - pupitriCatch.addToSign(bean.getSign(), beanWeight); - - } else { - notFoundSpecies.add(speciesId); - } - } - } - result = notFoundSpecies.size(); - catchBatch.setCatchTotalSortedCarousselWeight(carrouselSortedWeight); - - BatchContainer<SpeciesBatch> rootSpeciesBatch = persistenceService.getRootSpeciesBatch(operation.getId(), null); - for (SpeciesBatch batch : rootSpeciesBatch.getChildren()) { - persistenceService.deleteSpeciesBatch(batch.getId()); - } - - TuttiEnumerationFile enumerationFile = persistenceService.getEnumerationFile(); - - for (PupitriCatch pupitriCatch : catches) { - - Float catchWeight = pupitriCatch.getWeightBySign().get(PupitriCatch.Signs.DEFAULT); - CaracteristicQualitativeValue cqv = pupitriCatch.isSorted() ? - sortedCaracteristic : unsortedCaracteristic; - - Species species = pupitriCatch.getSpecies(); - - SpeciesBatch batch = createSpeciesBatch(operation, - species, - catchWeight, - enumerationFile.PMFM_ID_SORTED_UNSORTED, - cqv); - - batch = persistenceService.createSpeciesBatch(batch, null); - - // if the batch is splitted - if (catchWeight == null) { - Integer categoryId = null; - for (PupitriCatch.Signs s : pupitriCatch.getWeightBySign().keySet()) { - CaracteristicQualitativeValue splitCqv = null; - switch (s) { - case MALE: - categoryId = enumerationFile.PMFM_ID_SEX; - splitCqv = maleCaracteristic; - break; - - case FEMALE: - categoryId = enumerationFile.PMFM_ID_SEX; - splitCqv = femaleCaracteristic; - break; - - case SMALL: - categoryId = enumerationFile.PMFM_ID_SIZE_CATEGORY; - splitCqv = smallCaracteristic; - break; - - case MEDIUM: - categoryId = enumerationFile.PMFM_ID_SIZE_CATEGORY; - splitCqv = mediumCaracteristic; - break; - - case BIG: - categoryId = enumerationFile.PMFM_ID_SIZE_CATEGORY; - splitCqv = bigCaracteristic; - break; - } - - SpeciesBatch childBatch = createSpeciesBatch( - operation, - species, - pupitriCatch.getWeightBySign().get(s), - categoryId, - splitCqv - ); - - persistenceService.createSpeciesBatch(childBatch, batch.getId()); - } - } - } - - carrouselImporter.close(); - reader.close(); - - } catch (Exception e) { - DecoratorService service = getService(DecoratorService.class); - throw new TuttiTechnicalException(_("tutti.service.pupitri.import.carrousel.error", carrouselFile, service.getDecorator(operation).toString(operation)), e);//"Could not import carrousel data [" + operation.toString() + "] from file " + carrouselFile - - } finally { - IOUtils.closeQuietly(carrouselImporter); - IOUtils.closeQuietly(reader); - FileUtils.deleteQuietly(fileWithHeaders); - } - - return result; - } - - - public void exportSpecies(List<Species> species, File target) { - SpeciesRowModel speciesCsvModel = new SpeciesRowModel(';'); - - List<SpeciesRow> rows = Lists.newArrayList(); - - if (CollectionUtils.isNotEmpty(species)) { - rows = Lists.transform(species, new Function<Species, SpeciesRow>() { - - public SpeciesRow apply(Species input) { - Preconditions.checkNotNull(input.getSurveyCode(), - "Unable to export a species with a null survey code : " + input); - SpeciesRow row = new SpeciesRow(); - String codeFirstPart = StringUtils.substring(input.getSurveyCode(), 0, 4); - row.setCodeFirstPart(StringUtils.rightPad(codeFirstPart, 4)); - String codeSecondPart = StringUtils.substring(input.getSurveyCode(), 4, 7); - row.setCodeSecondPart(StringUtils.rightPad(codeSecondPart, 3)); - row.setScientificName(input.getName()); - return row; - } - }); - } - - try { - Export.exportToFile(speciesCsvModel, rows, target, Charsets.UTF_8, false); - - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.pupitri.export.species.error", target), e); - } - } - - protected SpeciesBatch createSpeciesBatch(FishingOperation operation, - Species species, - Float catchWeight, - Integer categoryId, - Serializable cqv) { - SpeciesBatch batch = TuttiBeanFactory.newSpeciesBatch(); - batch.setFishingOperation(operation); - batch.setSampleCategoryId(categoryId); - batch.setSampleCategoryValue(cqv); - batch.setSpecies(species); - batch.setSampleCategoryWeight(catchWeight); - return batch; - } - - protected File createFileWithHeaders(File file, String[] header, char separator) throws IOException { - File fileWithHeaders = new File(FileUtils.getTempDirectory(), file.getName()); - String headers = StringUtils.join(header, separator); - - FileUtils.writeLines(fileWithHeaders, Collections.singletonList(headers)); - FileUtils.writeLines(fileWithHeaders, FileUtils.readLines(file), true); - - return fileWithHeaders; - } -} Copied: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/ReferentialImportExportService.java (from rev 1246, trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportService.java) =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/ReferentialImportExportService.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/ReferentialImportExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,443 @@ +package fr.ifremer.tutti.service.referential; + +/* + * #%L + * Tutti :: Service + * $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.Charsets; +import com.google.common.base.Function; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.google.common.io.Files; +import fr.ifremer.tutti.TuttiTechnicalException; +import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; +import fr.ifremer.tutti.persistence.entities.referential.Gear; +import fr.ifremer.tutti.persistence.entities.referential.Person; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import fr.ifremer.tutti.persistence.entities.referential.Vessel; +import fr.ifremer.tutti.service.AbstractTuttiService; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.csv.Export; +import org.nuiton.csv.Import; +import org.nuiton.csv.ImportRuntimeException; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n._; + +/** + * Service to import or export referential. + * + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +public class ReferentialImportExportService extends AbstractTuttiService { + + /** Logger. */ + private static final Log log = + LogFactory.getLog(ReferentialImportExportService.class); + + protected PersistenceService persistenceService; + + @Override + public void setServiceContext(TuttiServiceContext context) { + super.setServiceContext(context); + persistenceService = getService(PersistenceService.class); + } + + public List<Species> importTemporarySpecies(File file) throws IOException { + + if (log.isInfoEnabled()) { + log.info("Will import species from file: " + file); + } + + // get all species names + Set<String> existingSpeciesName = Sets.newHashSet(Iterables.transform(persistenceService.getAllSpecies(), new Function<Species, String>() { + @Override + public String apply(Species input) { + return input.getName(); + } + })); + + List<Species> toImport = Lists.newArrayList(); + + Reader reader = Files.newReader(file, Charsets.UTF_8); + SpeciesModel csvModel = new SpeciesModel(getCsvSeparator(), existingSpeciesName); + try { + Import<Species> importer = Import.newImport(csvModel, reader); + + try { + + for (Species bean : importer) { + toImport.add(bean); + } + importer.close(); + } finally { + IOUtils.closeQuietly(importer); + } + reader.close(); + + } catch (IOException e) { + throw new IOException(_("tutti.service.referential.import.species.error", file), e); + + } catch (ImportRuntimeException e) { + String message; + if (e.getCause() != null) { + message = e.getCause().getMessage(); + } else { + message = e.getMessage(); + } + throw new TuttiTechnicalException(message, e); + + } finally { + + IOUtils.closeQuietly(reader); + } + + List<Species> result = + persistenceService.importTemporarySpecies(toImport); + return result; + } + + public List<Vessel> importTemporaryVessel(File file) throws IOException { + if (log.isInfoEnabled()) { + log.info("Will import vessels from file: " + file); + } + + // get all vessels + List<Vessel> existingVessels = Lists.newArrayList(persistenceService.getAllFishingVessel()); + existingVessels.addAll(persistenceService.getAllScientificVessel()); + + Function<Vessel, String> vesselToId = new Function<Vessel, String>() { + @Override + public String apply(Vessel input) { + return input.getName()+"#"+input.getInternationalRegistrationCode(); + } + }; + + Set<String> existingIds = Sets.newHashSet( + Lists.transform(existingVessels, vesselToId)); + + List<Vessel> toImport = Lists.newArrayList(); + + Reader reader = Files.newReader(file, Charsets.UTF_8); + VesselModel csvModel = new VesselModel(getCsvSeparator()); + try { + Import<Vessel> importer = Import.newImport(csvModel, reader); + + try { + + for (final Vessel bean : importer) { + + String currentId = vesselToId.apply(bean); + + if (!existingIds.add(currentId)) { + + // id was already in universe + throw new TuttiTechnicalException( + _("tutti.service.referential.import.vessels.existingValue.error", + bean.getName(), + bean.getInternationalRegistrationCode())); + } + toImport.add(bean); + } + importer.close(); + } finally { + IOUtils.closeQuietly(importer); + } + reader.close(); + } catch (IOException e) { + throw new IOException(_("tutti.service.referential.import.vessels.error", file), e); + } finally { + + IOUtils.closeQuietly(reader); + } + List<Vessel> result = + persistenceService.importTemporaryVessel(toImport); + return result; + } + + public List<Person> importTemporaryPerson(File file) throws IOException { + if (log.isInfoEnabled()) { + log.info("Will import persons from file: " + file); + } + + List<Person> toImport = Lists.newArrayList(); + + Reader reader = Files.newReader(file, Charsets.UTF_8); + PersonModel csvModel = new PersonModel(getCsvSeparator()); + try { + Import<Person> importer = Import.newImport(csvModel, reader); + + try { + + for (Person bean : importer) { + toImport.add(bean); + } + importer.close(); + } finally { + IOUtils.closeQuietly(importer); + } + reader.close(); + } catch (IOException e) { + throw new IOException(_("tutti.service.referential.import.persons.error", file), e); + } finally { + + IOUtils.closeQuietly(reader); + } + List<Person> result = + persistenceService.importTemporaryPerson(toImport); + return result; + } + + public List<Gear> importTemporaryGear(File file) throws IOException { + if (log.isInfoEnabled()) { + log.info("Will import gears from file: " + file); + } + + // get all vessel names + Set<String> existingGearName = Sets.newHashSet(Iterables.transform(persistenceService.getAllFishingGear(), new Function<Gear, String>() { + @Override + public String apply(Gear input) { + return input.getName(); + } + })); + + existingGearName.addAll(Lists.transform(persistenceService.getAllScientificGear(), new Function<Gear, String>() { + @Override + public String apply(Gear input) { + return input.getName(); + } + })); + + List<Gear> toImport = Lists.newArrayList(); + + Reader reader = Files.newReader(file, Charsets.UTF_8); + GearModel csvModel = new GearModel(getCsvSeparator(), existingGearName); + try { + Import<Gear> importer = Import.newImport(csvModel, reader); + + try { + + for (Gear bean : importer) { + toImport.add(bean); + } + importer.close(); + } finally { + IOUtils.closeQuietly(importer); + } + reader.close(); + } catch (IOException e) { + throw new IOException(_("tutti.service.referential.import.gears.error", file), e); + + } catch (ImportRuntimeException e) { + String message; + if (e.getCause() != null) { + message = e.getCause().getMessage(); + } else { + message = e.getMessage(); + } + throw new TuttiTechnicalException(message, e); + + } finally { + + IOUtils.closeQuietly(reader); + } + List<Gear> result = persistenceService.importTemporaryGear(toImport); + return result; + } + + public void exportTemporarySpeciesExample(File file) throws IOException { + + List<Species> toExport = Lists.newArrayList(); + + Species s; + + s = TuttiBeanFactory.newSpecies(); + s.setName("Temporary Species name 1"); + toExport.add(s); + + s = TuttiBeanFactory.newSpecies(); + s.setName("Temporary Species name 2"); + toExport.add(s); + + s = TuttiBeanFactory.newSpecies(); + s.setName("Temporary Species name 3"); + toExport.add(s); + + SpeciesModel csvModel = new SpeciesModel(getCsvSeparator(), null); + + BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); + try { + Export export = Export.newExport(csvModel, toExport); + export.write(writer); + writer.close(); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.referential.export.species.error", file), e); + } finally { + IOUtils.closeQuietly(writer); + } + + } + + public void exportTemporaryVesselExample(File file) throws IOException { + List<Vessel> toExport = Lists.newArrayList(); + + Vessel v; + + v = TuttiBeanFactory.newVessel(); + v.setName("Temporary fishing vessel name 1"); + v.setInternationalRegistrationCode("International registration code F1"); + v.setScientificVessel(false); + toExport.add(v); + + v = TuttiBeanFactory.newVessel(); + v.setName("Temporary fishing vessel name 2"); + v.setInternationalRegistrationCode("International registration code F2"); + v.setScientificVessel(false); + toExport.add(v); + + v = TuttiBeanFactory.newVessel(); + v.setName("Temporary scientific vessel name 3"); + v.setInternationalRegistrationCode("International registration code S3"); + v.setScientificVessel(true); + toExport.add(v); + + v = TuttiBeanFactory.newVessel(); + v.setName("Temporary scientific vessel name 4"); + v.setInternationalRegistrationCode("International registration code S4"); + v.setScientificVessel(true); + toExport.add(v); + + VesselModel csvModel = new VesselModel(getCsvSeparator()); + + BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); + try { + Export export = Export.newExport(csvModel, toExport); + export.write(writer); + writer.close(); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.referential.export.vessel.error", file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + public void exportTemporaryPersonExample(File file) throws IOException { + List<Person> toExport = Lists.newArrayList(); + + Person p; + + p = TuttiBeanFactory.newPerson(); + p.setFirstName("First name 1"); + p.setLastName("Last name 1"); + toExport.add(p); + + p = TuttiBeanFactory.newPerson(); + p.setFirstName("First name 2"); + p.setLastName("Last name 2"); + toExport.add(p); + + p = TuttiBeanFactory.newPerson(); + p.setFirstName("First name 3"); + p.setLastName("Last name 3"); + toExport.add(p); + + + PersonModel csvModel = new PersonModel(getCsvSeparator()); + + BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); + try { + Export export = Export.newExport(csvModel, toExport); + export.write(writer); + writer.close(); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.referential.export.person.error", file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + public void exportTemporaryGearExample(File file) throws IOException { + List<Gear> toExport = Lists.newArrayList(); + + Gear g; + + g = TuttiBeanFactory.newGear(); + g.setName("Gear fishing name 1"); + g.setLabel("Gear fishing label 1"); + toExport.add(g); + + g = TuttiBeanFactory.newGear(); + g.setName("Gear fishing name 2"); + g.setLabel("Gear fishing label 2"); + toExport.add(g); + + g = TuttiBeanFactory.newGear(); + g.setName("Gear scientific name 3"); + g.setLabel("Gear scientific label 3"); + g.setScientificGear(true); + toExport.add(g); + + g = TuttiBeanFactory.newGear(); + g.setName("Gear scientific name 4"); + g.setLabel("Gear scientific label 4"); + g.setScientificGear(true); + toExport.add(g); + + GearModel csvModel = new GearModel(getCsvSeparator(), null); + + BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); + try { + Export export = Export.newExport(csvModel, toExport); + export.write(writer); + writer.close(); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.referential.export.gear.error", file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + protected char getCsvSeparator() { + return context.getConfig().getCsvSeparator(); + } +} Deleted: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,446 +0,0 @@ -package fr.ifremer.tutti.service.referential; - -/* - * #%L - * Tutti :: Service - * $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.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.common.io.Files; -import fr.ifremer.tutti.TuttiTechnicalException; -import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; -import fr.ifremer.tutti.persistence.entities.referential.Gear; -import fr.ifremer.tutti.persistence.entities.referential.Person; -import fr.ifremer.tutti.persistence.entities.referential.Species; -import fr.ifremer.tutti.persistence.entities.referential.Vessel; -import fr.ifremer.tutti.service.AbstractTuttiService; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.csv.Export; -import org.nuiton.csv.Import; -import org.nuiton.csv.ImportRuntimeException; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n._; - -/** - * Service to import or export referential. - * - * @author tchemit <chemit@codelutin.com> - * @since 1.0 - */ -public class TuttiReferentialImportExportService extends AbstractTuttiService { - - /** Logger. */ - private static final Log log = - LogFactory.getLog(TuttiReferentialImportExportService.class); - - protected PersistenceService persistenceService; - - @Override - public void setServiceContext(TuttiServiceContext context) { - super.setServiceContext(context); - persistenceService = getService(PersistenceService.class); - } - - public List<Species> importTemporarySpecies(File file) throws IOException { - - if (log.isInfoEnabled()) { - log.info("Will import species from file: " + file); - } - - // get all species names - Set<String> existingSpeciesName = Sets.newHashSet(Iterables.transform(persistenceService.getAllSpecies(), new Function<Species, String>() { - @Override - public String apply(Species input) { - return input.getName(); - } - })); - - List<Species> toImport = Lists.newArrayList(); - - Reader reader = Files.newReader(file, Charsets.UTF_8); - SpeciesModel csvModel = new SpeciesModel(getCsvSeparator(), existingSpeciesName); - try { - Import<Species> importer = Import.newImport(csvModel, reader); - - try { - - for (Species bean : importer) { - toImport.add(bean); - } - importer.close(); - } finally { - IOUtils.closeQuietly(importer); - } - reader.close(); - - } catch (IOException e) { - throw new IOException(_("tutti.service.referential.import.species.error", file), e); - - } catch (ImportRuntimeException e) { - String message; - if (e.getCause() != null) { - message = e.getCause().getMessage(); - } else { - message = e.getMessage(); - } - throw new TuttiTechnicalException(message, e); - - } finally { - - IOUtils.closeQuietly(reader); - } - - List<Species> result = - persistenceService.importTemporarySpecies(toImport); - return result; - } - - public List<Vessel> importTemporaryVessel(File file) throws IOException { - if (log.isInfoEnabled()) { - log.info("Will import vessels from file: " + file); - } - - // get all vessels - List<Vessel> existingVessels = Lists.newArrayList(persistenceService.getAllFishingVessel()); - existingVessels.addAll(persistenceService.getAllScientificVessel()); - - Function<Vessel, String> vesselToId = new Function<Vessel, String>() { - @Override - public String apply(Vessel input) { - return input.getName()+"#"+input.getInternationalRegistrationCode(); - } - }; - - Set<String> existingIds = Sets.newHashSet( - Lists.transform(existingVessels, vesselToId)); - - List<Vessel> toImport = Lists.newArrayList(); - - Reader reader = Files.newReader(file, Charsets.UTF_8); - VesselModel csvModel = new VesselModel(getCsvSeparator()); - try { - Import<Vessel> importer = Import.newImport(csvModel, reader); - - try { - - for (final Vessel bean : importer) { - - String currentId = vesselToId.apply(bean); - - if (!existingIds.add(currentId)) { - - // id was already in universe - throw new TuttiTechnicalException( - _("tutti.service.referential.import.vessels.existingValue.error", - bean.getName(), - bean.getInternationalRegistrationCode())); - } - toImport.add(bean); - } - importer.close(); - } finally { - IOUtils.closeQuietly(importer); - } - reader.close(); - } catch (IOException e) { - throw new IOException(_("tutti.service.referential.import.vessels.error", file), e); - } finally { - - IOUtils.closeQuietly(reader); - } - List<Vessel> result = - persistenceService.importTemporaryVessel(toImport); - return result; - } - - public List<Person> importTemporaryPerson(File file) throws IOException { - if (log.isInfoEnabled()) { - log.info("Will import persons from file: " + file); - } - - List<Person> toImport = Lists.newArrayList(); - - Reader reader = Files.newReader(file, Charsets.UTF_8); - PersonModel csvModel = new PersonModel(getCsvSeparator()); - try { - Import<Person> importer = Import.newImport(csvModel, reader); - - try { - - for (Person bean : importer) { - toImport.add(bean); - } - importer.close(); - } finally { - IOUtils.closeQuietly(importer); - } - reader.close(); - } catch (IOException e) { - throw new IOException(_("tutti.service.referential.import.persons.error", file), e); - } finally { - - IOUtils.closeQuietly(reader); - } - List<Person> result = - persistenceService.importTemporaryPerson(toImport); - return result; - } - - public List<Gear> importTemporaryGear(File file) throws IOException { - if (log.isInfoEnabled()) { - log.info("Will import gears from file: " + file); - } - - // get all vessel names - Set<String> existingGearName = Sets.newHashSet(Iterables.transform(persistenceService.getAllFishingGear(), new Function<Gear, String>() { - @Override - public String apply(Gear input) { - return input.getName(); - } - })); - - existingGearName.addAll(Lists.transform(persistenceService.getAllScientificGear(), new Function<Gear, String>() { - @Override - public String apply(Gear input) { - return input.getName(); - } - })); - - List<Gear> toImport = Lists.newArrayList(); - - Reader reader = Files.newReader(file, Charsets.UTF_8); - GearModel csvModel = new GearModel(getCsvSeparator(), existingGearName); - try { - Import<Gear> importer = Import.newImport(csvModel, reader); - - try { - - for (Gear bean : importer) { - toImport.add(bean); - } - importer.close(); - } finally { - IOUtils.closeQuietly(importer); - } - reader.close(); - } catch (IOException e) { - throw new IOException(_("tutti.service.referential.import.gears.error", file), e); - - } catch (ImportRuntimeException e) { - String message; - if (e.getCause() != null) { - message = e.getCause().getMessage(); - } else { - message = e.getMessage(); - } - throw new TuttiTechnicalException(message, e); - - } finally { - - IOUtils.closeQuietly(reader); - } - List<Gear> result = persistenceService.importTemporaryGear(toImport); - return result; - } - - public void exportTemporarySpeciesExample(File file) throws IOException { - - List<Species> toExport = Lists.newArrayList(); - - Species s; - - s = TuttiBeanFactory.newSpecies(); - s.setName("Temporary Species name 1"); - toExport.add(s); - - s = TuttiBeanFactory.newSpecies(); - s.setName("Temporary Species name 2"); - toExport.add(s); - - s = TuttiBeanFactory.newSpecies(); - s.setName("Temporary Species name 3"); - toExport.add(s); - - SpeciesModel csvModel = new SpeciesModel(getCsvSeparator(), null); - - BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); - try { - Export export = Export.newExport(csvModel, toExport); - export.write(writer); - writer.close(); - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.referential.export.species.error", file), e); - } finally { - IOUtils.closeQuietly(writer); - } - - } - - public void exportTemporaryVesselExample(File file) throws IOException { - List<Vessel> toExport = Lists.newArrayList(); - - Vessel v; - - v = TuttiBeanFactory.newVessel(); - v.setName("Temporary fishing vessel name 1"); - v.setInternationalRegistrationCode("International registration code F1"); - v.setScientificVessel(false); - toExport.add(v); - - v = TuttiBeanFactory.newVessel(); - v.setName("Temporary fishing vessel name 2"); - v.setInternationalRegistrationCode("International registration code F2"); - v.setScientificVessel(false); - toExport.add(v); - - v = TuttiBeanFactory.newVessel(); - v.setName("Temporary scientific vessel name 3"); - v.setInternationalRegistrationCode("International registration code S3"); - v.setScientificVessel(true); - toExport.add(v); - - v = TuttiBeanFactory.newVessel(); - v.setName("Temporary scientific vessel name 4"); - v.setInternationalRegistrationCode("International registration code S4"); - v.setScientificVessel(true); - toExport.add(v); - - VesselModel csvModel = new VesselModel(getCsvSeparator()); - - BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); - try { - Export export = Export.newExport(csvModel, toExport); - export.write(writer); - writer.close(); - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.referential.export.vessel.error", file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - public void exportTemporaryPersonExample(File file) throws IOException { - List<Person> toExport = Lists.newArrayList(); - - Person p; - - p = TuttiBeanFactory.newPerson(); - p.setFirstName("First name 1"); - p.setLastName("Last name 1"); - toExport.add(p); - - p = TuttiBeanFactory.newPerson(); - p.setFirstName("First name 2"); - p.setLastName("Last name 2"); - toExport.add(p); - - p = TuttiBeanFactory.newPerson(); - p.setFirstName("First name 3"); - p.setLastName("Last name 3"); - toExport.add(p); - - - PersonModel csvModel = new PersonModel(getCsvSeparator()); - - BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); - try { - Export export = Export.newExport(csvModel, toExport); - export.write(writer); - writer.close(); - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.referential.export.person.error", file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - public void exportTemporaryGearExample(File file) throws IOException { - List<Gear> toExport = Lists.newArrayList(); - - Gear g; - - g = TuttiBeanFactory.newGear(); - g.setName("Gear fishing name 1"); - g.setLabel("Gear fishing label 1"); - toExport.add(g); - - g = TuttiBeanFactory.newGear(); - g.setName("Gear fishing name 2"); - g.setLabel("Gear fishing label 2"); - toExport.add(g); - - g = TuttiBeanFactory.newGear(); - g.setName("Gear scientific name 3"); - g.setLabel("Gear scientific label 3"); - g.setScientificGear(true); - toExport.add(g); - - g = TuttiBeanFactory.newGear(); - g.setName("Gear scientific name 4"); - g.setLabel("Gear scientific label 4"); - g.setScientificGear(true); - toExport.add(g); - - GearModel csvModel = new GearModel(getCsvSeparator(), null); - - BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); - try { - Export export = Export.newExport(csvModel, toExport); - export.write(writer); - writer.close(); - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.referential.export.gear.error", file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - protected char getCsvSeparator() { - return context.getConfig().getCsvSeparator(); - } -} Copied: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/CatchesSumatraExportService.java (from rev 1246, trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportService.java) =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/CatchesSumatraExportService.java (rev 0) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/CatchesSumatraExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,249 @@ +package fr.ifremer.tutti.service.sumatra; + +/* + * #%L + * Tutti :: Service + * $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.Charsets; +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.io.Files; +import fr.ifremer.tutti.TuttiTechnicalException; +import fr.ifremer.tutti.persistence.entities.TuttiEntities; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; +import fr.ifremer.tutti.persistence.entities.data.Cruise; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.SpeciesAbleBatch; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import fr.ifremer.tutti.service.AbstractTuttiService; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.TuttiServiceContext; +import fr.ifremer.tutti.service.catches.WeightComputingService; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.csv.Export; + +import java.io.BufferedWriter; +import java.io.File; +import java.util.List; +import java.util.Map; + +import static org.nuiton.i18n.I18n._; + +/** + * @author kmorin <kmorin@codelutin.com> + * @since 2.0 + */ +public class CatchesSumatraExportService extends AbstractTuttiService { + + private static final Log log = + LogFactory.getLog(CatchesSumatraExportService.class); + + protected PersistenceService persistenceService; + + protected WeightComputingService weightComputingService; + + @Override + public void setServiceContext(TuttiServiceContext context) { + super.setServiceContext(context); + persistenceService = getService(PersistenceService.class); + weightComputingService = getService(WeightComputingService.class); + } + + public void exportCruiseForSumatra(File file, + String cruiseId) { + + Preconditions.checkNotNull(cruiseId, "Cannot export a null cruise"); + Preconditions.checkNotNull(file, "Cannot export to a null file"); + + if (log.isInfoEnabled()) { + log.info("Will export cruise " + cruiseId + " to file: " + file); + } + + Cruise cruise = persistenceService.getCruise(cruiseId); + Preconditions.checkNotNull(cruise, "Cruise [" + cruiseId + "] not found"); + + CatchRowModel csvModel = + new CatchRowModel(context.getConfig().getCsvSeparator()); + List<CatchRow> rows = Lists.newArrayList(); + + List<FishingOperation> operations = persistenceService.getAllFishingOperation(cruiseId); + if (operations != null) { + for (FishingOperation operation : operations) { + + // add species rows + + BatchContainer<SpeciesBatch> speciesBatchContainer = + weightComputingService.getComputedSpeciesBatches(operation); + + Map<Species, CatchRow> rowMap = Maps.newLinkedHashMap(); + if (speciesBatchContainer != null) { + List<SpeciesBatch> speciesBatches = speciesBatchContainer.getChildren(); + for (SpeciesBatch batch : speciesBatches) { + Species sp = batch.getSpecies(); + + int number = Math.round(computeNumber(batch, 1.0f)); + + Float weight = TuttiEntities.getValueOrComputedValue( + batch.getSampleCategoryWeight(), + batch.getSampleCategoryComputedWeight()); + + + CatchRow row = rowMap.get(sp); + if (row == null) { + row = new CatchRow(); + row.setFishingOperation(operation); + row.setSpecies(sp); + row.setWeight(weight); + row.setNumber(number); + + } else { + row.setWeight(row.getWeight() + weight); + row.setNumber(row.getNumber() + number); + } + rowMap.put(sp, row); + } + rows.addAll(rowMap.values()); + } + + // add benthos rows + + BatchContainer<BenthosBatch> benthosBatchContainer = + weightComputingService.getComputedBenthosBatches(operation); + + rowMap.clear(); + if (benthosBatchContainer != null) { + List<BenthosBatch> benthosBatches = benthosBatchContainer.getChildren(); + for (BenthosBatch batch : benthosBatches) { + Species sp = batch.getSpecies(); + + Float weight = TuttiEntities.getValueOrComputedValue( + batch.getSampleCategoryWeight(), + batch.getSampleCategoryComputedWeight()); + + int number = Math.round(computeNumber(batch, 1.0f)); + + CatchRow row = rowMap.get(sp); + if (row == null) { + row = new CatchRow(); + row.setFishingOperation(operation); + row.setSpecies(sp); + row.setWeight(weight); + row.setNumber(number); + + } else { + row.setWeight(row.getWeight() + weight); + row.setNumber(row.getNumber() + number); + } + rowMap.put(sp, row); + } + } + + rows.addAll(rowMap.values()); + } + } + + BufferedWriter writer = null; + try { + writer = Files.newWriter(file, Charsets.UTF_8); + Export export = Export.newExport(csvModel, rows); + export.write(writer); + writer.close(); + + } catch (Exception e) { + throw new TuttiTechnicalException(_("tutti.service.sumatra.export.error", file), e); + } finally { + IOUtils.closeQuietly(writer); + } + } + + protected float computeNumber(SpeciesAbleBatch batch, float rf) { + float result; + + float weight = TuttiEntities.getValueOrComputedValue( + batch.getSampleCategoryWeight(), + batch.getSampleCategoryComputedWeight()); + + if (batch.isChildBatchsEmpty()) { + + // on a leaf, get his weight + + Integer number = TuttiEntities.getValueOrComputedValue( + batch.getNumber(), + batch.getComputedNumber()); + if (number == null) { + + // no count + number = 0; + +// // try to get frequency +// List<SpeciesBatchFrequency> frequencies = +// persistenceService.getAllSpeciesBatchFrequency(batch.getId()); +// if (CollectionUtils.isNotEmpty(frequencies)) { +// +// for (SpeciesBatchFrequency frequency : frequencies) { +// number += frequency.getNumber(); +// } +// } + } + + // get the sample weight + Float subweight = TuttiEntities.getValueOrComputedValue( + batch.getWeight(), + batch.getComputedWeight()); + + if (subweight != null) { + + // with sub sample, update the raising factor + rf *= weight / subweight; + } + + result = number.floatValue() * rf; + } else { + + // get total weight of all childs + float totalWeight = 0.f; + for (SpeciesAbleBatch child : batch.getChildBatchs()) { + totalWeight += TuttiEntities.getValueOrComputedValue( + child.getSampleCategoryWeight(), + child.getSampleCategoryComputedWeight()); + } + + result = 0f; + + float rf2 = rf * weight / totalWeight; + // sum result of each child + for (SpeciesAbleBatch child : batch.getChildBatchs()) { + + result += computeNumber(child, rf2); + } + + } + return result; + } + +} Deleted: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportService.java =================================================================== --- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportService.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportService.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,249 +0,0 @@ -package fr.ifremer.tutti.service.sumatra; - -/* - * #%L - * Tutti :: Service - * $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.Charsets; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.io.Files; -import fr.ifremer.tutti.TuttiTechnicalException; -import fr.ifremer.tutti.persistence.entities.TuttiEntities; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; -import fr.ifremer.tutti.persistence.entities.data.Cruise; -import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.data.SpeciesAbleBatch; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.persistence.entities.referential.Species; -import fr.ifremer.tutti.service.AbstractTuttiService; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.TuttiServiceContext; -import fr.ifremer.tutti.service.catches.TuttiWeightComputingService; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.csv.Export; - -import java.io.BufferedWriter; -import java.io.File; -import java.util.List; -import java.util.Map; - -import static org.nuiton.i18n.I18n._; - -/** - * @author kmorin <kmorin@codelutin.com> - * @since 2.0 - */ -public class TuttiCatchesSumatraExportService extends AbstractTuttiService { - - private static final Log log = - LogFactory.getLog(TuttiCatchesSumatraExportService.class); - - protected PersistenceService persistenceService; - - protected TuttiWeightComputingService tuttiWeightComputingService; - - @Override - public void setServiceContext(TuttiServiceContext context) { - super.setServiceContext(context); - persistenceService = getService(PersistenceService.class); - tuttiWeightComputingService = getService(TuttiWeightComputingService.class); - } - - public void exportCruiseForSumatra(File file, - String cruiseId) { - - Preconditions.checkNotNull(cruiseId, "Cannot export a null cruise"); - Preconditions.checkNotNull(file, "Cannot export to a null file"); - - if (log.isInfoEnabled()) { - log.info("Will export cruise " + cruiseId + " to file: " + file); - } - - Cruise cruise = persistenceService.getCruise(cruiseId); - Preconditions.checkNotNull(cruise, "Cruise [" + cruiseId + "] not found"); - - CatchRowModel csvModel = - new CatchRowModel(context.getConfig().getCsvSeparator()); - List<CatchRow> rows = Lists.newArrayList(); - - List<FishingOperation> operations = persistenceService.getAllFishingOperation(cruiseId); - if (operations != null) { - for (FishingOperation operation : operations) { - - // add species rows - - BatchContainer<SpeciesBatch> speciesBatchContainer = - tuttiWeightComputingService.getComputedSpeciesBatches(operation); - - Map<Species, CatchRow> rowMap = Maps.newLinkedHashMap(); - if (speciesBatchContainer != null) { - List<SpeciesBatch> speciesBatches = speciesBatchContainer.getChildren(); - for (SpeciesBatch batch : speciesBatches) { - Species sp = batch.getSpecies(); - - int number = Math.round(computeNumber(batch, 1.0f)); - - Float weight = TuttiEntities.getValueOrComputedValue( - batch.getSampleCategoryWeight(), - batch.getSampleCategoryComputedWeight()); - - - CatchRow row = rowMap.get(sp); - if (row == null) { - row = new CatchRow(); - row.setFishingOperation(operation); - row.setSpecies(sp); - row.setWeight(weight); - row.setNumber(number); - - } else { - row.setWeight(row.getWeight() + weight); - row.setNumber(row.getNumber() + number); - } - rowMap.put(sp, row); - } - rows.addAll(rowMap.values()); - } - - // add benthos rows - - BatchContainer<BenthosBatch> benthosBatchContainer = - tuttiWeightComputingService.getComputedBenthosBatches(operation); - - rowMap.clear(); - if (benthosBatchContainer != null) { - List<BenthosBatch> benthosBatches = benthosBatchContainer.getChildren(); - for (BenthosBatch batch : benthosBatches) { - Species sp = batch.getSpecies(); - - Float weight = TuttiEntities.getValueOrComputedValue( - batch.getSampleCategoryWeight(), - batch.getSampleCategoryComputedWeight()); - - int number = Math.round(computeNumber(batch, 1.0f)); - - CatchRow row = rowMap.get(sp); - if (row == null) { - row = new CatchRow(); - row.setFishingOperation(operation); - row.setSpecies(sp); - row.setWeight(weight); - row.setNumber(number); - - } else { - row.setWeight(row.getWeight() + weight); - row.setNumber(row.getNumber() + number); - } - rowMap.put(sp, row); - } - } - - rows.addAll(rowMap.values()); - } - } - - BufferedWriter writer = null; - try { - writer = Files.newWriter(file, Charsets.UTF_8); - Export export = Export.newExport(csvModel, rows); - export.write(writer); - writer.close(); - - } catch (Exception e) { - throw new TuttiTechnicalException(_("tutti.service.sumatra.export.error", file), e); - } finally { - IOUtils.closeQuietly(writer); - } - } - - protected float computeNumber(SpeciesAbleBatch batch, float rf) { - float result; - - float weight = TuttiEntities.getValueOrComputedValue( - batch.getSampleCategoryWeight(), - batch.getSampleCategoryComputedWeight()); - - if (batch.isChildBatchsEmpty()) { - - // on a leaf, get his weight - - Integer number = TuttiEntities.getValueOrComputedValue( - batch.getNumber(), - batch.getComputedNumber()); - if (number == null) { - - // no count - number = 0; - -// // try to get frequency -// List<SpeciesBatchFrequency> frequencies = -// persistenceService.getAllSpeciesBatchFrequency(batch.getId()); -// if (CollectionUtils.isNotEmpty(frequencies)) { -// -// for (SpeciesBatchFrequency frequency : frequencies) { -// number += frequency.getNumber(); -// } -// } - } - - // get the sample weight - Float subweight = TuttiEntities.getValueOrComputedValue( - batch.getWeight(), - batch.getComputedWeight()); - - if (subweight != null) { - - // with sub sample, update the raising factor - rf *= weight / subweight; - } - - result = number.floatValue() * rf; - } else { - - // get total weight of all childs - float totalWeight = 0.f; - for (SpeciesAbleBatch child : batch.getChildBatchs()) { - totalWeight += TuttiEntities.getValueOrComputedValue( - child.getSampleCategoryWeight(), - child.getSampleCategoryComputedWeight()); - } - - result = 0f; - - float rf2 = rf * weight / totalWeight; - // sum result of each child - for (SpeciesAbleBatch child : batch.getChildBatchs()) { - - result += computeNumber(child, rf2); - } - - } - return result; - } - -} Modified: trunk/tutti-service/src/main/resources/i18n/tutti-service_en_GB.properties =================================================================== --- trunk/tutti-service/src/main/resources/i18n/tutti-service_en_GB.properties 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/resources/i18n/tutti-service_en_GB.properties 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,3 +1,8 @@ +tutti.common.unit= +tutti.common.unit.g= +tutti.common.unit.kg= +tutti.common.unit.short.g= +tutti.common.unit.short.kg= tutti.config.option.basedir.description= tutti.config.option.csv.separator.description= tutti.config.option.data.directory.description= @@ -8,6 +13,11 @@ tutti.config.option.site.url.description= tutti.config.option.tmp.directory.description= tutti.config.option.version.description= +tutti.config.option.weight.unit.accidentalCatch.description= +tutti.config.option.weight.unit.benthos.description= +tutti.config.option.weight.unit.individualObservation.description= +tutti.config.option.weight.unit.marineLitter.description= +tutti.config.option.weight.unit.species.description= tutti.config.service= tutti.property.attachment= tutti.property.caracteristic= @@ -101,6 +111,8 @@ tutti.service.multipost.import.weights.error= tutti.service.multipost.import.wrongOperation.error= tutti.service.multipost.uncompress.error= +tutti.service.operations.cleanWeights.benthos.batch= +tutti.service.operations.cleanWeights.species.batch= tutti.service.operations.computeWeights.error.benthos.incoherentCategoryWeight= tutti.service.operations.computeWeights.error.benthos.incoherentParentCategoryWeight= tutti.service.operations.computeWeights.error.benthos.incoherentRowWeightCategory= Modified: trunk/tutti-service/src/main/resources/i18n/tutti-service_fr_FR.properties =================================================================== --- trunk/tutti-service/src/main/resources/i18n/tutti-service_fr_FR.properties 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/main/resources/i18n/tutti-service_fr_FR.properties 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,3 +1,8 @@ +tutti.common.unit= +tutti.common.unit.g= +tutti.common.unit.kg= +tutti.common.unit.short.g= +tutti.common.unit.short.kg= tutti.config.option.basedir.description=Répertoire principale tutti.config.option.csv.separator.description=Caractère séparateur pour les import / export de fichier au format csv. tutti.config.option.data.directory.description=Répertoire de données de l'application. Vous pouvez utiliser l'expression ${tutti.data.directory} pour le référence dans d'autres propriétés de configuration (ex\: ${tutti.data.directory}/tmp). @@ -8,6 +13,11 @@ tutti.config.option.site.url.description=Url du site internet de l'application tutti.config.option.tmp.directory.description=Répertoire temporaire utilisée par l'application (est nettoyé à chaque démarrage de l'application). tutti.config.option.version.description=Version courante de l'application +tutti.config.option.weight.unit.accidentalCatch.description=Unité de poids à utiliser dans la saisies des captures accidentelles +tutti.config.option.weight.unit.benthos.description=Unité de poids à utiliser dans la saisies du benthos +tutti.config.option.weight.unit.individualObservation.description=Unité de poids à utiliser dans la saisies des données individuelles +tutti.config.option.weight.unit.marineLitter.description=Unité de poids à utiliser dans la saisies des macro-déchêts +tutti.config.option.weight.unit.species.description=Unité de poids à utiliser dans la saisies des espèces tutti.config.service=Configuration des services de l'application tutti.property.attachment=Pièce jointe tutti.property.caracteristic=Caractéristique @@ -101,6 +111,11 @@ tutti.service.multipost.import.weights.error=Erreur lors de l'import des poids tutti.service.multipost.import.wrongOperation.error=Opération est impossible<hr/>Les lots que vous essayez d'importer proviennent d'un autre trait \:<br/>%s tutti.service.multipost.uncompress.error=Erreur lors de la décompression de l'archive %s +tutti.service.operations.cleanWeights.benthos.batch=Lot benthos +tutti.service.operations.cleanWeights.error.redundant.frequencyWeight=Le poids (%s%s) du <strong>sous-échantillon</strong> vaut la somme des poids des <strong>échantillons mesurés</strong> +tutti.service.operations.cleanWeights.error.redundant.sampleCategoryWeight=Le poids (%s%s) de la catégorie <strong>%s</strong> vaut celui de la catégorie supérieure <strong>%s</strong> +tutti.service.operations.cleanWeights.error.redundant.weight=Le poids (%s%s) de <strong>sous-échantillon</strong> vaut celui de la plus fine catégorie <strong>%s</strong> +tutti.service.operations.cleanWeights.species.batch=Lot espèce tutti.service.operations.computeWeights.error.benthos.incoherentCategoryWeight=Benthos - Le poids total des mensurations du lot de %s/%s - %s (%skg) est supérieur au poids de la catégorie (%skg) tutti.service.operations.computeWeights.error.benthos.incoherentParentCategoryWeight=Benthos - Le poids du lot de %s/%s - %s (%skg) est inférieur à la somme des poids de ses sous-catégories (%skg) tutti.service.operations.computeWeights.error.benthos.incoherentRowWeightCategory=Le poids de sous-échantillon est renseigné alors que le lot n'a pas de poids. Modified: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/ServiceDbResource.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/ServiceDbResource.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/ServiceDbResource.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -39,7 +39,7 @@ import fr.ifremer.tutti.persistence.test.DatabaseResource; import fr.ifremer.tutti.service.config.TuttiServiceConfig; import fr.ifremer.tutti.service.config.TuttiServiceConfigOption; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.Pair; @@ -201,10 +201,10 @@ public TuttiProtocol loadProtocol(File protocolFile) { Assert.assertTrue(protocolFile.exists()); - TuttiProtocolImportExportService tuttiProtocolImportExportService = - getServiceContext().getService(TuttiProtocolImportExportService.class); + ProtocolImportExportService protocolImportExportService = + getServiceContext().getService(ProtocolImportExportService.class); - TuttiProtocol protocol = tuttiProtocolImportExportService.importProtocol(protocolFile); + TuttiProtocol protocol = protocolImportExportService.importProtocol(protocolFile); return protocol; } Deleted: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingServiceTest.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingServiceTest.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,228 +0,0 @@ -package fr.ifremer.tutti.service.catches; - -/* - * #%L - * Tutti :: Service - * $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.TuttiBusinessException; -import fr.ifremer.tutti.persistence.entities.data.*; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.ServiceDbResource; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; - -import java.util.List; - -/** - * @author kmorin <kmorin@codelutin.com> - * @since 2.3 - */ -public class TuttiWeightComputingServiceTest { - - /** Logger. */ - private static final Log log = - LogFactory.getLog(TuttiWeightComputingServiceTest.class); - - @ClassRule - public static final ServiceDbResource dbResource = - ServiceDbResource.readDb("dbCGFS"); - - public static final String PROGRAM_ID = "CAM-CGFS"; - - public static final String CRUISE_ID = "100002"; - - /* the one with the batches to compute */ - public static final String OPERATION_1_ID = "100108"; - - /* the one with the total species weight less than the sum of the batches */ - public static final String OPERATION_2_ID = "100109"; - - /* the one with the total benthos weight less than the sum of the batches */ - public static final String OPERATION_3_ID = "100110"; - - /* the one with the total marine litter weight less than the sum of the batches */ - public static final String OPERATION_4_ID = "100111"; - - /* the one with the total catch weight different from the sum of the sorted and unsorted total weight */ - public static final String OPERATION_5_ID = "100112"; - - /* the one with the total catch weight different from the rejected weight */ - public static final String OPERATION_6_ID = "100113"; - - /* the one working */ - public static final String OPERATION_7_ID = "100114"; - - protected TuttiWeightComputingService tuttiWeightComputingService; - - protected PersistenceService persistenceService; - - @Before - public void setUp() throws Exception { - TuttiServiceContext serviceContext = dbResource.getServiceContext(); - - persistenceService = serviceContext.getService(PersistenceService.class); - - serviceContext.getDataContext().open(serviceContext.getConfig(), persistenceService); - tuttiWeightComputingService = serviceContext.getService(TuttiWeightComputingService.class); - } - - @Test - public void computeCatchWeights() { - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_2_ID); - try { - BatchContainer<SpeciesBatch> batches = persistenceService.getRootSpeciesBatch(OPERATION_2_ID, null); - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, batches, null, null); - Assert.fail(); - - } catch (TuttiBusinessException e) { - //ok, it is supposed to throw an exception - if (log.isInfoEnabled()) { - log.info("expected error on operation #2 : " + e.getMessage()); - } - } - - catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_3_ID); - try { - BatchContainer<BenthosBatch> batches = persistenceService.getRootBenthosBatch(OPERATION_3_ID, null); - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, null, batches, null); - Assert.fail(); - - } catch (TuttiBusinessException e) { - //ok, it is supposed to throw an exception - if (log.isInfoEnabled()) { - log.info("expected error on operation #3 : " + e.getMessage()); - } - } - - catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_4_ID); - try { - BatchContainer<MarineLitterBatch> batches = persistenceService.getRootMarineLitterBatch(OPERATION_4_ID); - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, null, null, batches); - Assert.fail(); - - } catch (TuttiBusinessException e) { - //ok, it is supposed to throw an exception - if (log.isInfoEnabled()) { - log.info("expected error on operation #4 : " + e.getMessage()); - } - } - - catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_5_ID); - try { - BatchContainer<SpeciesBatch> speciesBatches = persistenceService.getRootSpeciesBatch(OPERATION_5_ID, null); - BatchContainer<BenthosBatch> benthosBatches = persistenceService.getRootBenthosBatch(OPERATION_5_ID, null); - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, speciesBatches, benthosBatches, null); - Assert.fail(); - - } catch (TuttiBusinessException e) { - //ok, it is supposed to throw an exception - if (log.isInfoEnabled()) { - log.info("expected error on operation #5 : " + e.getMessage()); - } - } - - catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_6_ID); - try { - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, null, null, null); - Assert.fail(); - - } catch (TuttiBusinessException e) { - //ok, it is supposed to throw an exception - if (log.isInfoEnabled()) { - log.info("expected error on operation #6 : " + e.getMessage()); - } - } - - catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_7_ID); - try { - BatchContainer<SpeciesBatch> speciesBatches = persistenceService.getRootSpeciesBatch(OPERATION_7_ID, null); - BatchContainer<BenthosBatch> benthosBatches = persistenceService.getRootBenthosBatch(OPERATION_7_ID, null); - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, speciesBatches, benthosBatches, null); - if (log.isInfoEnabled()) { - log.info("Weight computing worked on operation #7"); - } - - } catch (TuttiBusinessException e) { - Assert.fail(); - } - } - - @Test - public void computeSpeciesBatch() { - BatchContainer<SpeciesBatch> speciesBatchContainer = persistenceService.getRootSpeciesBatch(OPERATION_1_ID, null); - List<SpeciesBatch> speciesBatches = speciesBatchContainer.getChildren(); - for (int i = 0 ; i < speciesBatches.size() - 1 ; i++) { - try { - SpeciesBatch batch = speciesBatches.get(i); - tuttiWeightComputingService.computeSpeciesBatch(batch); - Assert.fail(); - } catch (TuttiBusinessException e) { - //ok, it is supposed to throw an exception - if (log.isInfoEnabled()) { - log.info("expected error on species batch #" + i + " : " + e.getMessage()); - } - } - } - SpeciesBatch speciesBatch = speciesBatches.get(speciesBatches.size() - 1); - try { - tuttiWeightComputingService.computeSpeciesBatch(speciesBatch); - if (log.isInfoEnabled()) { - log.info("last species batch weight computing worked"); - } - - } catch (TuttiBusinessException e) { - Assert.fail(); - } - - BatchContainer<BenthosBatch> benthosBatchContainer = persistenceService.getRootBenthosBatch(OPERATION_1_ID, null); - List<BenthosBatch> benthosBatches = benthosBatchContainer.getChildren(); - for (int i = 0 ; i < benthosBatches.size() - 1 ; i++) { - try { - BenthosBatch batch = benthosBatches.get(i); - tuttiWeightComputingService.computeBenthosBatch(batch); - Assert.fail(); - } catch (TuttiBusinessException e) { - //ok, it is supposed to throw an exception - if (log.isInfoEnabled()) { - log.info("expected error on species batch #" + i + " : " + e.getMessage()); - } - } - } - BenthosBatch benthosBatch = benthosBatches.get(benthosBatches.size() - 1); - try { - tuttiWeightComputingService.computeBenthosBatch(benthosBatch); - if (log.isInfoEnabled()) { - log.info("last benthos batch weight computing worked"); - } - - } catch (TuttiBusinessException e) { - Assert.fail(); - } - } - -} Copied: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/WeightComputingServiceTest.java (from rev 1246, trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/TuttiWeightComputingServiceTest.java) =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/WeightComputingServiceTest.java (rev 0) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/WeightComputingServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,228 @@ +package fr.ifremer.tutti.service.catches; + +/* + * #%L + * Tutti :: Service + * $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.TuttiBusinessException; +import fr.ifremer.tutti.persistence.entities.data.*; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.ServiceDbResource; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import java.util.List; + +/** + * @author kmorin <kmorin@codelutin.com> + * @since 2.3 + */ +public class WeightComputingServiceTest { + + /** Logger. */ + private static final Log log = + LogFactory.getLog(WeightComputingServiceTest.class); + + @ClassRule + public static final ServiceDbResource dbResource = + ServiceDbResource.readDb("dbCGFS"); + + public static final String PROGRAM_ID = "CAM-CGFS"; + + public static final String CRUISE_ID = "100002"; + + /* the one with the batches to compute */ + public static final String OPERATION_1_ID = "100108"; + + /* the one with the total species weight less than the sum of the batches */ + public static final String OPERATION_2_ID = "100109"; + + /* the one with the total benthos weight less than the sum of the batches */ + public static final String OPERATION_3_ID = "100110"; + + /* the one with the total marine litter weight less than the sum of the batches */ + public static final String OPERATION_4_ID = "100111"; + + /* the one with the total catch weight different from the sum of the sorted and unsorted total weight */ + public static final String OPERATION_5_ID = "100112"; + + /* the one with the total catch weight different from the rejected weight */ + public static final String OPERATION_6_ID = "100113"; + + /* the one working */ + public static final String OPERATION_7_ID = "100114"; + + protected WeightComputingService weightComputingService; + + protected PersistenceService persistenceService; + + @Before + public void setUp() throws Exception { + TuttiServiceContext serviceContext = dbResource.getServiceContext(); + + persistenceService = serviceContext.getService(PersistenceService.class); + + serviceContext.getDataContext().open(serviceContext.getConfig(), persistenceService); + weightComputingService = serviceContext.getService(WeightComputingService.class); + } + + @Test + public void computeCatchWeights() { + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_2_ID); + try { + BatchContainer<SpeciesBatch> batches = persistenceService.getRootSpeciesBatch(OPERATION_2_ID, null); + weightComputingService.computeCatchBatchWeights(catchBatch, batches, null, null); + Assert.fail(); + + } catch (TuttiBusinessException e) { + //ok, it is supposed to throw an exception + if (log.isInfoEnabled()) { + log.info("expected error on operation #2 : " + e.getMessage()); + } + } + + catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_3_ID); + try { + BatchContainer<BenthosBatch> batches = persistenceService.getRootBenthosBatch(OPERATION_3_ID, null); + weightComputingService.computeCatchBatchWeights(catchBatch, null, batches, null); + Assert.fail(); + + } catch (TuttiBusinessException e) { + //ok, it is supposed to throw an exception + if (log.isInfoEnabled()) { + log.info("expected error on operation #3 : " + e.getMessage()); + } + } + + catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_4_ID); + try { + BatchContainer<MarineLitterBatch> batches = persistenceService.getRootMarineLitterBatch(OPERATION_4_ID); + weightComputingService.computeCatchBatchWeights(catchBatch, null, null, batches); + Assert.fail(); + + } catch (TuttiBusinessException e) { + //ok, it is supposed to throw an exception + if (log.isInfoEnabled()) { + log.info("expected error on operation #4 : " + e.getMessage()); + } + } + + catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_5_ID); + try { + BatchContainer<SpeciesBatch> speciesBatches = persistenceService.getRootSpeciesBatch(OPERATION_5_ID, null); + BatchContainer<BenthosBatch> benthosBatches = persistenceService.getRootBenthosBatch(OPERATION_5_ID, null); + weightComputingService.computeCatchBatchWeights(catchBatch, speciesBatches, benthosBatches, null); + Assert.fail(); + + } catch (TuttiBusinessException e) { + //ok, it is supposed to throw an exception + if (log.isInfoEnabled()) { + log.info("expected error on operation #5 : " + e.getMessage()); + } + } + + catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_6_ID); + try { + weightComputingService.computeCatchBatchWeights(catchBatch, null, null, null); + Assert.fail(); + + } catch (TuttiBusinessException e) { + //ok, it is supposed to throw an exception + if (log.isInfoEnabled()) { + log.info("expected error on operation #6 : " + e.getMessage()); + } + } + + catchBatch = persistenceService.getCatchBatchFromFishingOperation(OPERATION_7_ID); + try { + BatchContainer<SpeciesBatch> speciesBatches = persistenceService.getRootSpeciesBatch(OPERATION_7_ID, null); + BatchContainer<BenthosBatch> benthosBatches = persistenceService.getRootBenthosBatch(OPERATION_7_ID, null); + weightComputingService.computeCatchBatchWeights(catchBatch, speciesBatches, benthosBatches, null); + if (log.isInfoEnabled()) { + log.info("Weight computing worked on operation #7"); + } + + } catch (TuttiBusinessException e) { + Assert.fail(); + } + } + + @Test + public void computeSpeciesBatch() { + BatchContainer<SpeciesBatch> speciesBatchContainer = persistenceService.getRootSpeciesBatch(OPERATION_1_ID, null); + List<SpeciesBatch> speciesBatches = speciesBatchContainer.getChildren(); + for (int i = 0 ; i < speciesBatches.size() - 1 ; i++) { + try { + SpeciesBatch batch = speciesBatches.get(i); + weightComputingService.computeSpeciesBatch(batch); + Assert.fail(); + } catch (TuttiBusinessException e) { + //ok, it is supposed to throw an exception + if (log.isInfoEnabled()) { + log.info("expected error on species batch #" + i + " : " + e.getMessage()); + } + } + } + SpeciesBatch speciesBatch = speciesBatches.get(speciesBatches.size() - 1); + try { + weightComputingService.computeSpeciesBatch(speciesBatch); + if (log.isInfoEnabled()) { + log.info("last species batch weight computing worked"); + } + + } catch (TuttiBusinessException e) { + Assert.fail(); + } + + BatchContainer<BenthosBatch> benthosBatchContainer = persistenceService.getRootBenthosBatch(OPERATION_1_ID, null); + List<BenthosBatch> benthosBatches = benthosBatchContainer.getChildren(); + for (int i = 0 ; i < benthosBatches.size() - 1 ; i++) { + try { + BenthosBatch batch = benthosBatches.get(i); + weightComputingService.computeBenthosBatch(batch); + Assert.fail(); + } catch (TuttiBusinessException e) { + //ok, it is supposed to throw an exception + if (log.isInfoEnabled()) { + log.info("expected error on species batch #" + i + " : " + e.getMessage()); + } + } + } + BenthosBatch benthosBatch = benthosBatches.get(benthosBatches.size() - 1); + try { + weightComputingService.computeBenthosBatch(benthosBatch); + if (log.isInfoEnabled()) { + log.info("last benthos batch weight computing worked"); + } + + } catch (TuttiBusinessException e) { + Assert.fail(); + } + } + +} Copied: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/MultiPostExportServiceTest.java (from rev 1246, trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportServiceTest.java) =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/MultiPostExportServiceTest.java (rev 0) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/MultiPostExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,260 @@ +package fr.ifremer.tutti.service.catches.multipost; + +/* + * #%L + * Tutti :: Service + * $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.io.Files; +import fr.ifremer.tutti.service.ServiceDbResource; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import java.io.File; + +/** + * @author tchemit <chemit@codelutin.com> + * @since 2.4 + * //FIXME Add more data in db + */ +public class MultiPostExportServiceTest { + + @ClassRule + public static final ServiceDbResource dbResource = + ServiceDbResource.readDb("dbCGFS"); + + public static final String PROGRAM_ID = "CAM-CGFS"; + + public static final String CRUISE_ID = "100001"; + + public static final String OPERATION_1_ID = "100106"; + + public static final String OPERATION_2_ID = "100107"; + + public static final String SPECIES_CONTENT = "id;parentId;species;categoryId;categoryValue;categoryWeight;weight;number;comment;toConfirm\n" + + "CatchRow_1;;11242;1428;311;100.0;;;;N;\n" + + "CatchRow_2;CatchRow_1;11242;198;305;80.0;;;;N;\n" + + "CatchRow_3;CatchRow_2;11242;196;300;30.0;;;;N;\n" + + "CatchRow_4;CatchRow_3;11242;174;272;10.0;5.0;;;N;\n" + + "CatchRow_5;CatchRow_3;11242;174;274;10.0;;;;N;\n" + + "CatchRow_6;CatchRow_2;11242;196;301;50.0;30.0;;;N;\n" + + "CatchRow_7;CatchRow_1;11242;198;306;20.0;;;;N;\n" + + "CatchRow_8;;11242;1428;310;20.0;;2;;N;"; + + public static final String SPECIES_FREQUENCIES_CONTENT = "batchId;lengthStepCaracteristic;lengthStep;number;weight\n" + + "CatchRow_4;307;10.0;5;;\n" + + "CatchRow_4;307;10.5;2;;\n" + + "CatchRow_4;307;11.0;1;;\n" + + "CatchRow_5;307;11.0;5;;\n" + + "CatchRow_6;1425;10.0;5;;\n" + + "CatchRow_6;1425;11.0;6;;\n" + + "CatchRow_6;1425;12.0;7;;"; + + public static final String SPECIES_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date;totalSortedWeight;inertWeight;livingNotItemizedWeight\n" + + "A;1;1;01/05/2013 00:00;;;;"; + + public static final String SPECIES_ATTACHMENT_CONTENT = "batchId;name;comment;file"; + + + public static final String BENTHOS_CONTENT = "id;parentId;species;categoryId;categoryValue;categoryWeight;weight;number;comment;toConfirm"; + + public static final String BENTHOS_FREQUENCIES_CONTENT = "batchId;lengthStepCaracteristic;lengthStep;number;weight"; + + public static final String BENTHOS_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date;totalSortedWeight;inertWeight;livingNotItemizedWeight\n" + + "A;1;1;01/05/2013 00:00;;;;"; + + public static final String BENTHOS_ATTACHMENT_CONTENT = "batchId;name;comment;file"; + + public static final String MARINE_LITTER_CONTENT = "batchId;category;sizeCategory;number;weight;comment\n" + + "MarineLitterRow_1;2119;2120;2;5.0;S1;\n" + + "MarineLitterRow_2;2126;2121;3;1.0;S2;"; + + public static final String MARINE_LITTER_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date;totalWeight\n" + + "A;1;1;01/05/2013 00:00;;"; + + public static final String ACCIDENTAL_CATCH_CONTENT = "batchId;species;gender;weight;size;lengthStepCaracteristic;deadOrAlive;comment\n" + + "AccidentalCatchRow_1;3835;301;10.0;4.0;1425;1769;;"; + + public static final String ACCIDENTAL_CATCH_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date\n" + + "A;1;1;01/05/2013 00:00;"; + + public static final String ACCIDENTAL_CATCH_CARACTERISTIC_CONTENT = "batchId;caracteristic;value"; + + public static final String ACCIDENTAL_CATCH_ATTACHMENT_CONTENT = "batchId;name;comment;file"; + + public static final String INDIVIDUAL_OBSERVATION_CONTENT = "batchId;species;weight;size;lengthStepCaracteristic;comment\n" + + "IndividualObservationRow_1;11242;0.1;10.0;307;P1;"; + + public static final String INDIVIDUAL_OBSERVATION_CARACTERISTIC_CONTENT = "batchId;caracteristic;value\n" + + "IndividualObservationRow_1;1436;10;\n" + + "IndividualObservationRow_1;1435;A20;\n" + + "IndividualObservationRow_1;101;10.0;\n" + + "IndividualObservationRow_1;46;168;\n" + + "IndividualObservationRow_1;1388;5.0;"; + + public static final String INDIVIDUAL_OBSERVATION_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date\n" + + "A;1;1;01/05/2013 00:00;"; + + public static final String MARINE_LITTER_ATTACHMENT_CONTENT = "batchId;name;comment;file"; + + public static final String INDIVIDUAL_OBSERVATION_ATTACHMENT_CONTENT = "batchId;name;comment;file"; + + protected MultiPostExportService service; + + protected ServiceDbResource.DataContext dataContext; + + protected File dataDirectory; + + @Before + public void setUp() throws Exception { + + dataDirectory = dbResource.getServiceConfig().getDataDirectory(); + + TuttiServiceContext serviceContext = dbResource.getServiceContext(); + + dbResource.openDataContext(); + + service = serviceContext.getService(MultiPostExportService.class); + + dataContext = dbResource.loadContext(PROGRAM_ID, + CRUISE_ID, + 2, + OPERATION_1_ID, + OPERATION_2_ID); + } + + @Test + public void testExportSpecies() throws Exception { + + File exportFile = new File(dataDirectory, + "exportSpecies.zip"); + + Files.createParentDirs(exportFile); + + Assert.assertFalse(exportFile.exists()); + + service.exportSpecies(exportFile, dataContext.operations.get(0)); + Assert.assertTrue(exportFile.exists()); + + dbResource.assertZipContent( + "Species export", + exportFile, + Pair.of(MultiPostExportService.FREQUENCIES_FILE, SPECIES_FREQUENCIES_CONTENT), + Pair.of(MultiPostExportService.SPECIES_FILE, SPECIES_CONTENT), + Pair.of(MultiPostExportService.WEIGHTS_FILE, SPECIES_WEIGHTS_CONTENT), + Pair.of(MultiPostExportService.ATTACHMENTS_FILE, SPECIES_ATTACHMENT_CONTENT) + ); + + } + + @Test + public void testExportBenthos() throws Exception { + File exportFile = new File(dataDirectory, + "exportBenthos.zip"); + + Files.createParentDirs(exportFile); + + Assert.assertFalse(exportFile.exists()); + + service.exportBenthos(exportFile, dataContext.operations.get(0)); + Assert.assertTrue(exportFile.exists()); + + dbResource.assertZipContent( + "Benthos export", + exportFile, + Pair.of(MultiPostExportService.FREQUENCIES_FILE, BENTHOS_FREQUENCIES_CONTENT), + Pair.of(MultiPostExportService.BENTHOS_FILE, BENTHOS_CONTENT), + Pair.of(MultiPostExportService.WEIGHTS_FILE, BENTHOS_WEIGHTS_CONTENT), + Pair.of(MultiPostExportService.ATTACHMENTS_FILE, BENTHOS_ATTACHMENT_CONTENT) + + ); + } + + @Test + public void testExportMarineLitter() throws Exception { + File exportFile = new File(dataDirectory, + "exportMarineLitter.zip"); + + Files.createParentDirs(exportFile); + + Assert.assertFalse(exportFile.exists()); + + service.exportMarineLitter(exportFile, dataContext.operations.get(0)); + Assert.assertTrue(exportFile.exists()); + + dbResource.assertZipContent( + "MarineLitter export", + exportFile, + Pair.of(MultiPostExportService.MARINE_LITTER_FILE, MARINE_LITTER_CONTENT), + Pair.of(MultiPostExportService.WEIGHTS_FILE, MARINE_LITTER_WEIGHTS_CONTENT), + Pair.of(MultiPostExportService.ATTACHMENTS_FILE, MARINE_LITTER_ATTACHMENT_CONTENT) + ); + } + + @Test + public void testExportIndividualObservation() throws Exception { + File exportFile = new File(dataDirectory, + "exportIndividualObservation.zip"); + + Files.createParentDirs(exportFile); + + Assert.assertFalse(exportFile.exists()); + + service.exportIndividualObservation(exportFile, dataContext.operations.get(0)); + Assert.assertTrue(exportFile.exists()); + + dbResource.assertZipContent( + "IndividualObservation export", + exportFile, + Pair.of(MultiPostExportService.INDIVIDUAL_OBSERVATION_FILE, INDIVIDUAL_OBSERVATION_CONTENT), + Pair.of(MultiPostExportService.CARACTERISTIC_FILE, INDIVIDUAL_OBSERVATION_CARACTERISTIC_CONTENT), + Pair.of(MultiPostExportService.WEIGHTS_FILE, INDIVIDUAL_OBSERVATION_WEIGHTS_CONTENT), + Pair.of(MultiPostExportService.ATTACHMENTS_FILE, INDIVIDUAL_OBSERVATION_ATTACHMENT_CONTENT) + ); + } + + @Test + public void testExportAccidentalCatch() throws Exception { + File exportFile = new File(dataDirectory, + "exportAccidentalCatch.zip"); + + Files.createParentDirs(exportFile); + + Assert.assertFalse(exportFile.exists()); + + service.exportAccidentalCatch(exportFile, dataContext.operations.get(0)); + Assert.assertTrue(exportFile.exists()); + + dbResource.assertZipContent( + "AccidentalCatch export", + exportFile, + Pair.of(MultiPostExportService.ACCIDENTAL_CATCHES_FILE, ACCIDENTAL_CATCH_CONTENT), + Pair.of(MultiPostExportService.WEIGHTS_FILE, ACCIDENTAL_CATCH_WEIGHTS_CONTENT), + Pair.of(MultiPostExportService.CARACTERISTIC_FILE, ACCIDENTAL_CATCH_CARACTERISTIC_CONTENT), + Pair.of(MultiPostExportService.ATTACHMENTS_FILE, ACCIDENTAL_CATCH_ATTACHMENT_CONTENT) + ); + } +} Deleted: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportServiceTest.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportServiceTest.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/catches/multipost/TuttiMultiPostExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,260 +0,0 @@ -package fr.ifremer.tutti.service.catches.multipost; - -/* - * #%L - * Tutti :: Service - * $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.io.Files; -import fr.ifremer.tutti.service.ServiceDbResource; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.apache.commons.lang3.tuple.Pair; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; - -import java.io.File; - -/** - * @author tchemit <chemit@codelutin.com> - * @since 2.4 - * //FIXME Add more data in db - */ -public class TuttiMultiPostExportServiceTest { - - @ClassRule - public static final ServiceDbResource dbResource = - ServiceDbResource.readDb("dbCGFS"); - - public static final String PROGRAM_ID = "CAM-CGFS"; - - public static final String CRUISE_ID = "100001"; - - public static final String OPERATION_1_ID = "100106"; - - public static final String OPERATION_2_ID = "100107"; - - public static final String SPECIES_CONTENT = "id;parentId;species;categoryId;categoryValue;categoryWeight;weight;number;comment;toConfirm\n" + - "CatchRow_1;;11242;1428;311;100.0;;;;N;\n" + - "CatchRow_2;CatchRow_1;11242;198;305;80.0;;;;N;\n" + - "CatchRow_3;CatchRow_2;11242;196;300;30.0;;;;N;\n" + - "CatchRow_4;CatchRow_3;11242;174;272;10.0;5.0;;;N;\n" + - "CatchRow_5;CatchRow_3;11242;174;274;10.0;;;;N;\n" + - "CatchRow_6;CatchRow_2;11242;196;301;50.0;30.0;;;N;\n" + - "CatchRow_7;CatchRow_1;11242;198;306;20.0;;;;N;\n" + - "CatchRow_8;;11242;1428;310;20.0;;2;;N;"; - - public static final String SPECIES_FREQUENCIES_CONTENT = "batchId;lengthStepCaracteristic;lengthStep;number;weight\n" + - "CatchRow_4;307;10.0;5;;\n" + - "CatchRow_4;307;10.5;2;;\n" + - "CatchRow_4;307;11.0;1;;\n" + - "CatchRow_5;307;11.0;5;;\n" + - "CatchRow_6;1425;10.0;5;;\n" + - "CatchRow_6;1425;11.0;6;;\n" + - "CatchRow_6;1425;12.0;7;;"; - - public static final String SPECIES_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date;totalSortedWeight;inertWeight;livingNotItemizedWeight\n" + - "A;1;1;01/05/2013 00:00;;;;"; - - public static final String SPECIES_ATTACHMENT_CONTENT = "batchId;name;comment;file"; - - - public static final String BENTHOS_CONTENT = "id;parentId;species;categoryId;categoryValue;categoryWeight;weight;number;comment;toConfirm"; - - public static final String BENTHOS_FREQUENCIES_CONTENT = "batchId;lengthStepCaracteristic;lengthStep;number;weight"; - - public static final String BENTHOS_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date;totalSortedWeight;inertWeight;livingNotItemizedWeight\n" + - "A;1;1;01/05/2013 00:00;;;;"; - - public static final String BENTHOS_ATTACHMENT_CONTENT = "batchId;name;comment;file"; - - public static final String MARINE_LITTER_CONTENT = "batchId;category;sizeCategory;number;weight;comment\n" + - "MarineLitterRow_1;2119;2120;2;5.0;S1;\n" + - "MarineLitterRow_2;2126;2121;3;1.0;S2;"; - - public static final String MARINE_LITTER_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date;totalWeight\n" + - "A;1;1;01/05/2013 00:00;;"; - - public static final String ACCIDENTAL_CATCH_CONTENT = "batchId;species;gender;weight;size;lengthStepCaracteristic;deadOrAlive;comment\n" + - "AccidentalCatchRow_1;3835;301;10.0;4.0;1425;1769;;"; - - public static final String ACCIDENTAL_CATCH_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date\n" + - "A;1;1;01/05/2013 00:00;"; - - public static final String ACCIDENTAL_CATCH_CARACTERISTIC_CONTENT = "batchId;caracteristic;value"; - - public static final String ACCIDENTAL_CATCH_ATTACHMENT_CONTENT = "batchId;name;comment;file"; - - public static final String INDIVIDUAL_OBSERVATION_CONTENT = "batchId;species;weight;size;lengthStepCaracteristic;comment\n" + - "IndividualObservationRow_1;11242;0.1;10.0;307;P1;"; - - public static final String INDIVIDUAL_OBSERVATION_CARACTERISTIC_CONTENT = "batchId;caracteristic;value\n" + - "IndividualObservationRow_1;1436;10;\n" + - "IndividualObservationRow_1;1435;A20;\n" + - "IndividualObservationRow_1;101;10.0;\n" + - "IndividualObservationRow_1;46;168;\n" + - "IndividualObservationRow_1;1388;5.0;"; - - public static final String INDIVIDUAL_OBSERVATION_WEIGHTS_CONTENT = "stationNumber;operationNumber;multirigAggregation;date\n" + - "A;1;1;01/05/2013 00:00;"; - - public static final String MARINE_LITTER_ATTACHMENT_CONTENT = "batchId;name;comment;file"; - - public static final String INDIVIDUAL_OBSERVATION_ATTACHMENT_CONTENT = "batchId;name;comment;file"; - - protected TuttiMultiPostExportService service; - - protected ServiceDbResource.DataContext dataContext; - - protected File dataDirectory; - - @Before - public void setUp() throws Exception { - - dataDirectory = dbResource.getServiceConfig().getDataDirectory(); - - TuttiServiceContext serviceContext = dbResource.getServiceContext(); - - dbResource.openDataContext(); - - service = serviceContext.getService(TuttiMultiPostExportService.class); - - dataContext = dbResource.loadContext(PROGRAM_ID, - CRUISE_ID, - 2, - OPERATION_1_ID, - OPERATION_2_ID); - } - - @Test - public void testExportSpecies() throws Exception { - - File exportFile = new File(dataDirectory, - "exportSpecies.zip"); - - Files.createParentDirs(exportFile); - - Assert.assertFalse(exportFile.exists()); - - service.exportSpecies(exportFile, dataContext.operations.get(0)); - Assert.assertTrue(exportFile.exists()); - - dbResource.assertZipContent( - "Species export", - exportFile, - Pair.of(TuttiMultiPostExportService.FREQUENCIES_FILE, SPECIES_FREQUENCIES_CONTENT), - Pair.of(TuttiMultiPostExportService.SPECIES_FILE, SPECIES_CONTENT), - Pair.of(TuttiMultiPostExportService.WEIGHTS_FILE, SPECIES_WEIGHTS_CONTENT), - Pair.of(TuttiMultiPostExportService.ATTACHMENTS_FILE, SPECIES_ATTACHMENT_CONTENT) - ); - - } - - @Test - public void testExportBenthos() throws Exception { - File exportFile = new File(dataDirectory, - "exportBenthos.zip"); - - Files.createParentDirs(exportFile); - - Assert.assertFalse(exportFile.exists()); - - service.exportBenthos(exportFile, dataContext.operations.get(0)); - Assert.assertTrue(exportFile.exists()); - - dbResource.assertZipContent( - "Benthos export", - exportFile, - Pair.of(TuttiMultiPostExportService.FREQUENCIES_FILE, BENTHOS_FREQUENCIES_CONTENT), - Pair.of(TuttiMultiPostExportService.BENTHOS_FILE, BENTHOS_CONTENT), - Pair.of(TuttiMultiPostExportService.WEIGHTS_FILE, BENTHOS_WEIGHTS_CONTENT), - Pair.of(TuttiMultiPostExportService.ATTACHMENTS_FILE, BENTHOS_ATTACHMENT_CONTENT) - - ); - } - - @Test - public void testExportMarineLitter() throws Exception { - File exportFile = new File(dataDirectory, - "exportMarineLitter.zip"); - - Files.createParentDirs(exportFile); - - Assert.assertFalse(exportFile.exists()); - - service.exportMarineLitter(exportFile, dataContext.operations.get(0)); - Assert.assertTrue(exportFile.exists()); - - dbResource.assertZipContent( - "MarineLitter export", - exportFile, - Pair.of(TuttiMultiPostExportService.MARINE_LITTER_FILE, MARINE_LITTER_CONTENT), - Pair.of(TuttiMultiPostExportService.WEIGHTS_FILE, MARINE_LITTER_WEIGHTS_CONTENT), - Pair.of(TuttiMultiPostExportService.ATTACHMENTS_FILE, MARINE_LITTER_ATTACHMENT_CONTENT) - ); - } - - @Test - public void testExportIndividualObservation() throws Exception { - File exportFile = new File(dataDirectory, - "exportIndividualObservation.zip"); - - Files.createParentDirs(exportFile); - - Assert.assertFalse(exportFile.exists()); - - service.exportIndividualObservation(exportFile, dataContext.operations.get(0)); - Assert.assertTrue(exportFile.exists()); - - dbResource.assertZipContent( - "IndividualObservation export", - exportFile, - Pair.of(TuttiMultiPostExportService.INDIVIDUAL_OBSERVATION_FILE, INDIVIDUAL_OBSERVATION_CONTENT), - Pair.of(TuttiMultiPostExportService.CARACTERISTIC_FILE, INDIVIDUAL_OBSERVATION_CARACTERISTIC_CONTENT), - Pair.of(TuttiMultiPostExportService.WEIGHTS_FILE, INDIVIDUAL_OBSERVATION_WEIGHTS_CONTENT), - Pair.of(TuttiMultiPostExportService.ATTACHMENTS_FILE, INDIVIDUAL_OBSERVATION_ATTACHMENT_CONTENT) - ); - } - - @Test - public void testExportAccidentalCatch() throws Exception { - File exportFile = new File(dataDirectory, - "exportAccidentalCatch.zip"); - - Files.createParentDirs(exportFile); - - Assert.assertFalse(exportFile.exists()); - - service.exportAccidentalCatch(exportFile, dataContext.operations.get(0)); - Assert.assertTrue(exportFile.exists()); - - dbResource.assertZipContent( - "AccidentalCatch export", - exportFile, - Pair.of(TuttiMultiPostExportService.ACCIDENTAL_CATCHES_FILE, ACCIDENTAL_CATCH_CONTENT), - Pair.of(TuttiMultiPostExportService.WEIGHTS_FILE, ACCIDENTAL_CATCH_WEIGHTS_CONTENT), - Pair.of(TuttiMultiPostExportService.CARACTERISTIC_FILE, ACCIDENTAL_CATCH_CARACTERISTIC_CONTENT), - Pair.of(TuttiMultiPostExportService.ATTACHMENTS_FILE, ACCIDENTAL_CATCH_ATTACHMENT_CONTENT) - ); - } -} Modified: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/export/TuttiExportService2Test.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/export/TuttiExportService2Test.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/export/TuttiExportService2Test.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -31,7 +31,7 @@ import fr.ifremer.tutti.service.PersistenceService; import fr.ifremer.tutti.service.ServiceDbResource; import fr.ifremer.tutti.service.TuttiServiceContext; -import fr.ifremer.tutti.service.catches.TuttiWeightComputingService; +import fr.ifremer.tutti.service.catches.WeightComputingService; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; @@ -94,7 +94,7 @@ // check there is a error while compute weight for a cruise boolean errorDetected = false; - TuttiWeightComputingService computingService = serviceContext.getService(TuttiWeightComputingService.class); + WeightComputingService computingService = serviceContext.getService(WeightComputingService.class); List<FishingOperation> allFishingOperation = persistenceService.getAllFishingOperation(CRUISE_ID); for (FishingOperation fishingOperation : allFishingOperation) { try { @@ -116,7 +116,7 @@ ProgressionModel progressionModel = new ProgressionModel(); progressionModel.setTotal(9); try { - service.exportCruise(CRUISE_ID, null, exportFile, progressionModel); + service.exportCruise(CRUISE_ID, exportFile, progressionModel); // got an error after but export was still performed Assert.fail(); } catch (TuttiBusinessException e) { Modified: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/export/TuttiExportServiceTest.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/export/TuttiExportServiceTest.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/export/TuttiExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -232,7 +232,7 @@ Assert.assertFalse(exportFile.exists()); - service.exportProgram(dataContext.program.getId(), null, exportFile, progressionModel); + service.exportProgram(dataContext.program.getId(), exportFile, progressionModel); Assert.assertTrue(exportFile.exists()); } @@ -245,7 +245,7 @@ Assert.assertFalse(exportFile.exists()); - service.exportCruise(dataContext.cruise.getId(), null, exportFile, progressionModel); + service.exportCruise(dataContext.cruise.getId(), exportFile, progressionModel); Assert.assertTrue(exportFile.exists()); } @@ -253,7 +253,7 @@ public void exportSurvey() throws Exception { TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportSurvey(exportContext, dataContext.cruise); @@ -269,7 +269,7 @@ public void exportGearCaracteristics() throws Exception { TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportGearCaracteristics(exportContext, dataContext.cruise); @@ -287,7 +287,7 @@ // loadData(PROGRAM_ID, CRUISE_CGFS_ID); TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportOperations(exportContext, dataContext.cruise, dataContext.operations); @@ -308,7 +308,7 @@ dataContext.operations = Lists.newArrayList(operation); TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportOperations(exportContext, dataContext.cruise, dataContext.operations); @@ -331,7 +331,7 @@ dataContext.operations = Lists.newArrayList(operation); TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportOperations(exportContext, dataContext.cruise, dataContext.operations); @@ -348,7 +348,7 @@ public void exportParameters() throws Exception { TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportParameters(exportContext, dataContext.cruise, dataContext.operations); @@ -364,7 +364,7 @@ public void exportCatches() throws Exception { TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportCatches(exportContext, dataContext.cruise, dataContext.operations); @@ -390,7 +390,7 @@ dataContext.operations = Lists.newArrayList(operation); TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, protocol); + service.createExportContext(dataDirectory); try { service.exportCatches(exportContext, dataContext.cruise, dataContext.operations); @@ -417,7 +417,7 @@ dataContext = dbResource.loadContext(PROGRAM_ID, CRUISE_CGFS_ID, NB_EXPECTED_CGFS_OPERATIONS); TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportCatches(exportContext, dataContext.cruise, dataContext.operations); @@ -430,7 +430,7 @@ public void exportMarineLitters() throws Exception { TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportMarineLitters(exportContext, dataContext.cruise, dataContext.operations); @@ -446,7 +446,7 @@ public void exportIndividualObservations() throws Exception { TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportIndividualObservations(exportContext, dataContext.cruise, dataContext.operations); @@ -462,7 +462,7 @@ public void exportAccidentalCatch() throws Exception { TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { service.exportAccidentalCatch(exportContext, dataContext.cruise, dataContext.operations); @@ -478,7 +478,7 @@ public void exportSpecies() throws Exception { TuttiExportService.ExportContext exportContext = - service.createExportContext(dataDirectory, null); + service.createExportContext(dataDirectory); try { List<Species> allReferentSpecies = Copied: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/ProtocolImportExportServiceTest.java (from rev 1246, trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportServiceTest.java) =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/ProtocolImportExportServiceTest.java (rev 0) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/ProtocolImportExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,618 @@ +package fr.ifremer.tutti.service.protocol; + +/* + * #%L + * Tutti :: Service + * $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.Charsets; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.io.Files; +import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; +import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; +import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; +import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import fr.ifremer.tutti.service.ServiceDbResource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import java.io.File; +import java.util.Map; + +/** + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +public class ProtocolImportExportServiceTest { + + @ClassRule + public static final ServiceDbResource dbResource = + ServiceDbResource.writeDb("dbCGFS"); + + protected ProtocolImportExportService service; + + public static final int VRAC_HORS_VRAC = 1428; + + public static final int SIZE = 198; + + public static final int SEX = 196; + + public static final int MATURITY = 174; + + public static final int AGE = 1430; + + public static final String PROTOCOL_FILE_CONTENT = + "id: 1\n" + + "name: protocolName\n" + + "benthos: \n" + + "- !SpeciesProtocol\n" + + " id: 21\n" + + " calcifySampleEnabled: true\n" + + " lengthStepPmfmId: 1394\n" + + " mandatorySampleCategoryId: \n" + + " - 174\n" + + " - 196\n" + + " speciesReferenceTaxonId: 11242\n" + + " speciesSurveyCode: cruiseCode1\n" + + " weightEnabled: true\n" + + "- !SpeciesProtocol\n" + + " id: 22\n" + + " calcifySampleEnabled: true\n" + + " countIfNoFrequencyEnabled: true\n" + + " lengthStepPmfmId: 323\n" + + " mandatorySampleCategoryId: \n" + + " - 1430\n" + + " - 174\n" + + " - 196\n" + + " - 198\n" + + " speciesReferenceTaxonId: 3835\n" + + " weightEnabled: true\n" + + "comment: Commentaire\n" + + "gearUseFeaturePmfmId: \n" + + "- 21\n" + + "- 22\n" + + "lengthClassesPmfmId: \n" + + "- 14\n" + + "- 18\n" + + "species: \n" + + "- !SpeciesProtocol\n" + + " id: 1\n" + + " calcifySampleEnabled: true\n" + + " lengthStepPmfmId: 1394\n" + + " mandatorySampleCategoryId: \n" + + " - 174\n" + + " - 196\n" + + " speciesReferenceTaxonId: 11242\n" + + " speciesSurveyCode: cruiseCode1\n" + + " weightEnabled: true\n" + + "- !SpeciesProtocol\n" + + " id: 2\n" + + " calcifySampleEnabled: true\n" + + " countIfNoFrequencyEnabled: true\n" + + " lengthStepPmfmId: 323\n" + + " mandatorySampleCategoryId: \n" + + " - 1430\n" + + " - 174\n" + + " - 196\n" + + " - 198\n" + + " speciesReferenceTaxonId: 3835\n" + + " weightEnabled: true\n" + + "version: 2\n" + + "vesselUseFeaturePmfmId: \n" + + "- 114\n" + + "- 228\n" + + "- 821"; + + public static final String PROTOCOL_CARACTERISTIC_FILE_CONTENT = + "pmfmId;pmfmType;pmfmParameterName;pmfmMatrixName;pmfmFractionName;pmfmMethodName\n" + + "1;LENGTH_STEP;parameterName1;matrixName1;fractionName1;methodName1;\n" + + "2;VESSEL_USE_FEATURE;parameterName2;matrixName2;fractionName2;methodName2;\n" + + "3;GEAR_USE_FEATURE;parameterName3;matrixName3;fractionName3;methodName3;"; + + public static final String ALL_CARACTERISTIC_FILE_CONTENT = + "pmfmId;pmfmType;pmfmParameterName;pmfmMatrixName;pmfmFractionName;pmfmMethodName\n" + + "1;;parameterName1;matrixName1;fractionName1;methodName1;\n" + + "2;;parameterName2;matrixName2;fractionName2;methodName2;\n" + + "3;;parameterName3;matrixName3;fractionName3;methodName3;\n" + + "4;;parameterName4;matrixName4;fractionName4;methodName4;\n" + + "5;;parameterName5;matrixName5;fractionName5;methodName5;"; + + public static final String PROTOCOL_SPECIES_FILE_CONTENT = + "speciesReferenceTaxonId;speciesRefTaxCode;speciesName;speciesSurveyCode;lengthStepPmfmId;lengthStepPmfmParameterName;lengthStepPmfmMatrixName;lengthStepPmfmFractionName;lengthStepPmfmMethodName;mandatorySampleCategoryId;weightEnabled;countIfNoFrequencyEnabled;calcifySampleEnabled\n" + + "1;speciesRefTaxCode1;speciesName1;cruiseCode1;2;parameterName2;matrixName2;fractionName2;methodName2;1430|198|174|196;Y;Y;Y;\n" + + "2;speciesRefTaxCode2;speciesName2;;;;;;;1430|196;Y;Y;Y;"; + + public static final String PROTOCOL_BENTHOS_FILE_CONTENT = + "speciesReferenceTaxonId;speciesRefTaxCode;speciesName;speciesSurveyCode;lengthStepPmfmId;lengthStepPmfmParameterName;lengthStepPmfmMatrixName;lengthStepPmfmFractionName;lengthStepPmfmMethodName;mandatorySampleCategoryId;weightEnabled;countIfNoFrequencyEnabled;calcifySampleEnabled\n" + + "1;speciesRefTaxCode1;speciesName1;cruiseCode1;2;parameterName2;matrixName2;fractionName2;methodName2;1430|198|174|196;Y;Y;Y;\n" + + "2;speciesRefTaxCode2;speciesName2;;;;;;;1430|196;Y;Y;Y;"; + + File datadirectory; + + @Before + public void setUp() throws Exception { + + dbResource.getServiceConfig().setCsvSeparator(';'); + + service = dbResource.getServiceContext().getService( + ProtocolImportExportService.class); + + datadirectory = dbResource.getServiceConfig().getDataDirectory(); + } + + @Test + public void exportProtocol() throws Exception { + + File exportFile = new File(datadirectory, "exportProtocol.yaml"); + + Files.createParentDirs(exportFile); + + Assert.assertFalse(exportFile.exists()); + TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); + protocol.setVersion(2); + protocol.setId("1"); + protocol.setName("protocolName"); + protocol.setComment("Commentaire"); + protocol.setLengthClassesPmfmId(Lists.newArrayList("14", "18")); + protocol.setVesselUseFeaturePmfmId(Lists.newArrayList("114", "228", "821")); + protocol.setGearUseFeaturePmfmId(Lists.newArrayList("21", "22")); + + protocol.setSpecies(Lists.<SpeciesProtocol>newArrayList()); + SpeciesProtocol sp1 = TuttiBeanFactory.newSpeciesProtocol(); + sp1.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); + sp1.setId(1); + sp1.setSpeciesReferenceTaxonId(11242); + sp1.setSpeciesSurveyCode("cruiseCode1"); + sp1.setLengthStepPmfmId("1394"); + sp1.setCalcifySampleEnabled(true); + sp1.addMandatorySampleCategoryId(MATURITY); + sp1.addMandatorySampleCategoryId(SEX); + sp1.setWeightEnabled(true); + protocol.addSpecies(sp1); + + SpeciesProtocol sp2 = TuttiBeanFactory.newSpeciesProtocol(); + sp2.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); + sp2.setId(2); + sp2.setSpeciesReferenceTaxonId(3835); + sp2.setLengthStepPmfmId("323"); + sp2.addMandatorySampleCategoryId(AGE); + sp2.setCalcifySampleEnabled(true); + sp2.setCountIfNoFrequencyEnabled(true); + sp2.addMandatorySampleCategoryId(MATURITY); + sp2.addMandatorySampleCategoryId(SEX); + sp2.addMandatorySampleCategoryId(SIZE); + sp2.setWeightEnabled(true); + protocol.addSpecies(sp2); + + protocol.setBenthos(Lists.<SpeciesProtocol>newArrayList()); + SpeciesProtocol bp1 = TuttiBeanFactory.newSpeciesProtocol(); + bp1.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); + bp1.setId(21); + bp1.setSpeciesSurveyCode("cruiseCode1"); + bp1.setSpeciesReferenceTaxonId(11242); + bp1.setLengthStepPmfmId("1394"); + bp1.setCalcifySampleEnabled(true); + bp1.addMandatorySampleCategoryId(MATURITY); + bp1.addMandatorySampleCategoryId(SEX); + bp1.setWeightEnabled(true); + protocol.addBenthos(bp1); + + SpeciesProtocol bp2 = TuttiBeanFactory.newSpeciesProtocol(); + bp2.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); + bp2.setId(22); + bp2.setSpeciesReferenceTaxonId(3835); + bp2.setLengthStepPmfmId("323"); + bp2.addMandatorySampleCategoryId(AGE); + bp2.setCalcifySampleEnabled(true); + bp2.setCountIfNoFrequencyEnabled(true); + bp2.addMandatorySampleCategoryId(MATURITY); + bp2.addMandatorySampleCategoryId(SEX); + bp2.addMandatorySampleCategoryId(SIZE); + bp2.setWeightEnabled(true); + protocol.addBenthos(bp2); + + service.exportProtocol(protocol, exportFile); + Assert.assertTrue(exportFile.exists()); + + String exportFileToString = Files.toString(exportFile, Charsets.UTF_8).trim(); + Assert.assertEquals(PROTOCOL_FILE_CONTENT, exportFileToString); + } + + @Test + public void importProtocol() throws Exception { + + File importfile = new File(datadirectory, "importProtocol.yaml"); + + Files.createParentDirs(importfile); + + Files.write(PROTOCOL_FILE_CONTENT, importfile, Charsets.UTF_8); + + TuttiProtocol protocol = service.importProtocol(importfile); + + Assert.assertNotNull(protocol); + Assert.assertEquals("1", protocol.getId()); + Assert.assertEquals(2, protocol.getVersion(),0); + Assert.assertEquals("protocolName", protocol.getName()); + Assert.assertEquals("Commentaire", protocol.getComment()); + Assert.assertEquals(Lists.newArrayList("14", "18"), protocol.getLengthClassesPmfmId()); + Assert.assertEquals(Lists.newArrayList("114", "228", "821"), protocol.getVesselUseFeaturePmfmId()); + Assert.assertEquals(Lists.newArrayList("21", "22"), protocol.getGearUseFeaturePmfmId()); + + Assert.assertNotNull(protocol.getSpecies()); + Assert.assertEquals(2, protocol.sizeSpecies()); + SpeciesProtocol sp1 = protocol.getSpecies(0); + Assert.assertNotNull(sp1); + Assert.assertEquals(1, sp1.getIdAsInt(), 0); + Assert.assertEquals(11242, sp1.getSpeciesReferenceTaxonId(), 0); + Assert.assertEquals("cruiseCode1", sp1.getSpeciesSurveyCode()); + Assert.assertEquals("1394", sp1.getLengthStepPmfmId()); + Assert.assertFalse(sp1.containsMandatorySampleCategoryId(AGE)); + Assert.assertTrue(sp1.isCalcifySampleEnabled()); + Assert.assertFalse(sp1.isCountIfNoFrequencyEnabled()); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(MATURITY)); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SEX)); + Assert.assertFalse(sp1.containsMandatorySampleCategoryId(SIZE)); + Assert.assertTrue(sp1.isWeightEnabled()); + + SpeciesProtocol sp2 = protocol.getSpecies(1); + Assert.assertNotNull(sp2); + Assert.assertEquals(2, sp2.getIdAsInt(), 0); + Assert.assertEquals(3835, sp2.getSpeciesReferenceTaxonId(), 0); + Assert.assertEquals("323", sp2.getLengthStepPmfmId()); + Assert.assertTrue(sp2.containsMandatorySampleCategoryId(AGE)); + Assert.assertTrue(sp2.isCalcifySampleEnabled()); + Assert.assertTrue(sp2.isCountIfNoFrequencyEnabled()); + Assert.assertTrue(sp2.containsMandatorySampleCategoryId(MATURITY)); + Assert.assertTrue(sp2.containsMandatorySampleCategoryId(SEX)); + Assert.assertTrue(sp2.containsMandatorySampleCategoryId(SIZE)); + Assert.assertTrue(sp2.isWeightEnabled()); + + Assert.assertNotNull(protocol.getBenthos()); + Assert.assertEquals(2, protocol.sizeBenthos()); + SpeciesProtocol b1 = protocol.getBenthos(0); + Assert.assertNotNull(b1); + Assert.assertEquals(21, b1.getIdAsInt(), 0); + Assert.assertEquals(11242, b1.getSpeciesReferenceTaxonId(), 0); + Assert.assertEquals("cruiseCode1", b1.getSpeciesSurveyCode()); + Assert.assertEquals("1394", b1.getLengthStepPmfmId()); + Assert.assertFalse(b1.containsMandatorySampleCategoryId(AGE)); + Assert.assertTrue(b1.isCalcifySampleEnabled()); + Assert.assertFalse(b1.isCountIfNoFrequencyEnabled()); + Assert.assertTrue(b1.containsMandatorySampleCategoryId(MATURITY)); + Assert.assertTrue(b1.containsMandatorySampleCategoryId(SEX)); + Assert.assertFalse(b1.containsMandatorySampleCategoryId(SIZE)); + Assert.assertTrue(b1.isWeightEnabled()); + + SpeciesProtocol b2 = protocol.getBenthos(1); + Assert.assertNotNull(b2); + Assert.assertEquals(22, b2.getIdAsInt(), 0); + Assert.assertEquals(3835, b2.getSpeciesReferenceTaxonId(), 0); + Assert.assertEquals("323", b2.getLengthStepPmfmId()); + Assert.assertTrue(b2.containsMandatorySampleCategoryId(AGE)); + Assert.assertTrue(b2.isCalcifySampleEnabled()); + Assert.assertTrue(b2.isCountIfNoFrequencyEnabled()); + Assert.assertTrue(b2.containsMandatorySampleCategoryId(MATURITY)); + Assert.assertTrue(b2.containsMandatorySampleCategoryId(SEX)); + Assert.assertTrue(b2.containsMandatorySampleCategoryId(SIZE)); + Assert.assertTrue(b2.isWeightEnabled()); + } + + @Test + public void importProtocolCaracteristic() throws Exception { + + File file = new File(datadirectory, "importProtocolCaracteristic.csv"); + + Files.createParentDirs(file); + + Files.write(PROTOCOL_CARACTERISTIC_FILE_CONTENT, file, Charsets.UTF_8); + + TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); + Map<String, Caracteristic> caracteristicMap = createCaracteristics(); + + service.importProtocolCaracteristic(file, + protocol, + caracteristicMap); + + Assert.assertEquals(Lists.newArrayList("1"), + protocol.getLengthClassesPmfmId()); + Assert.assertEquals(Lists.newArrayList("2"), + protocol.getVesselUseFeaturePmfmId()); + Assert.assertEquals(Lists.newArrayList("3"), + protocol.getGearUseFeaturePmfmId()); + } + + @Test + public void exportProtocolCaracteristic() throws Exception { + + File file = new File(datadirectory, "exportProtocolCaracteristic.csv"); + + Files.createParentDirs(file); + + Map<String, Caracteristic> caracteristicMap = createCaracteristics(); + TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); + + protocol.setLengthClassesPmfmId(Lists.newArrayList("1")); + protocol.setVesselUseFeaturePmfmId(Lists.newArrayList("2")); + protocol.setGearUseFeaturePmfmId(Lists.newArrayList("3")); + + Assert.assertFalse(file.exists()); + service.exportProtocolCaracteristic(file, + protocol, + caracteristicMap); + + Assert.assertTrue(file.exists()); + + String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); + Assert.assertEquals(PROTOCOL_CARACTERISTIC_FILE_CONTENT, exportFileToString); + } + + @Test + public void exportAllCaracteristic() throws Exception { + + File file = new File(datadirectory, "exportAllCaracteristic.csv"); + + Files.createParentDirs(file); + + Map<String, Caracteristic> caracteristicMap = createCaracteristics(); + + Assert.assertFalse(file.exists()); + service.exportAllCaracteristic(file, caracteristicMap); + + Assert.assertTrue(file.exists()); + + String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); + Assert.assertEquals(ALL_CARACTERISTIC_FILE_CONTENT, exportFileToString); + } + + @Test + public void importProtocolSpecies() throws Exception { + + File file = new File(datadirectory, "importProtocolSpecies.csv"); + + Files.createParentDirs(file); + + Files.write(PROTOCOL_SPECIES_FILE_CONTENT, file, Charsets.UTF_8); + + TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); + Map<String, Species> speciesMap = createSpecies(); + Map<String, Caracteristic> caracteristicMap = createCaracteristics(); + + service.importProtocolSpecies(file, + protocol, + caracteristicMap, + speciesMap); + + Assert.assertEquals(2, protocol.sizeSpecies()); + + SpeciesProtocol sp1 = protocol.getSpecies().get(0); + Assert.assertNotNull(sp1); + Assert.assertEquals(1, sp1.getSpeciesReferenceTaxonId(), 0); + Assert.assertEquals("cruiseCode1", sp1.getSpeciesSurveyCode()); + Assert.assertEquals("2", sp1.getLengthStepPmfmId()); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(AGE)); + Assert.assertTrue(sp1.isCalcifySampleEnabled()); + Assert.assertTrue(sp1.isCountIfNoFrequencyEnabled()); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(MATURITY)); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SEX)); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SIZE)); + Assert.assertTrue(sp1.isWeightEnabled()); + + SpeciesProtocol sp2 = protocol.getSpecies().get(1); + Assert.assertNotNull(sp2); + Assert.assertEquals(2, sp2.getSpeciesReferenceTaxonId(), 0); + Assert.assertNull(sp2.getSpeciesSurveyCode()); + Assert.assertNull(sp2.getLengthStepPmfmId()); + Assert.assertTrue(sp2.containsMandatorySampleCategoryId(AGE)); + Assert.assertTrue(sp2.isCalcifySampleEnabled()); + Assert.assertTrue(sp2.isCountIfNoFrequencyEnabled()); + Assert.assertFalse(sp2.containsMandatorySampleCategoryId(MATURITY)); + Assert.assertTrue(sp2.containsMandatorySampleCategoryId(SEX)); + Assert.assertFalse(sp2.containsMandatorySampleCategoryId(SIZE)); + Assert.assertTrue(sp2.isWeightEnabled()); + } + + @Test + public void exportProtocolSpecies() throws Exception { + + File file = new File(datadirectory, "exportProtocolSpecies.csv"); + + Files.createParentDirs(file); + + Map<String, Species> speciesMap = createSpecies(); + + TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); + protocol.setSpecies(Lists.<SpeciesProtocol>newArrayList()); + + SpeciesProtocol sp1 = TuttiBeanFactory.newSpeciesProtocol(); + sp1.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); + sp1.setSpeciesReferenceTaxonId(1); + sp1.setSpeciesSurveyCode("cruiseCode1"); + sp1.addMandatorySampleCategoryId(AGE); + sp1.addMandatorySampleCategoryId(SIZE); + sp1.addMandatorySampleCategoryId(MATURITY); + sp1.addMandatorySampleCategoryId(SEX); + sp1.setWeightEnabled(true); + sp1.setCountIfNoFrequencyEnabled(true); + sp1.setCalcifySampleEnabled(true); + sp1.setLengthStepPmfmId("2"); + + protocol.addSpecies(sp1); + + SpeciesProtocol sp2 = TuttiBeanFactory.newSpeciesProtocol(); + sp2.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); + sp2.setSpeciesReferenceTaxonId(2); + sp2.addMandatorySampleCategoryId(AGE); + sp2.removeMandatorySampleCategoryId(SIZE); + sp2.removeMandatorySampleCategoryId(MATURITY); + sp2.addMandatorySampleCategoryId(SEX); + sp2.setWeightEnabled(true); + sp2.setCalcifySampleEnabled(true); + sp2.setCountIfNoFrequencyEnabled(true); + sp2.setLengthStepPmfmId(null); + + protocol.addSpecies(sp2); + + Assert.assertFalse(file.exists()); + service.exportProtocolSpecies(file, + protocol.getSpecies(), + createCaracteristics(), + speciesMap); + + Assert.assertTrue(file.exists()); + + String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); + Assert.assertEquals(PROTOCOL_SPECIES_FILE_CONTENT, exportFileToString); + } + + @Test + public void importProtocolBenthos() throws Exception { + + File file = new File(datadirectory, "importProtocolBenthos.csv"); + + Files.createParentDirs(file); + + Files.write(PROTOCOL_BENTHOS_FILE_CONTENT, file, Charsets.UTF_8); + + TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); + Map<String, Species> speciesMap = createSpecies(); + Map<String, Caracteristic> caracteristicMap = createCaracteristics(); + + service.importProtocolBenthos(file, + protocol, + caracteristicMap, + speciesMap); + + Assert.assertEquals(2, protocol.sizeBenthos()); + + SpeciesProtocol sp1 = protocol.getBenthos(0); + Assert.assertNotNull(sp1); + Assert.assertEquals(1, sp1.getSpeciesReferenceTaxonId(), 0); + Assert.assertEquals("cruiseCode1", sp1.getSpeciesSurveyCode()); + Assert.assertEquals("2", sp1.getLengthStepPmfmId()); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(AGE)); + Assert.assertTrue(sp1.isCalcifySampleEnabled()); + Assert.assertTrue(sp1.isCountIfNoFrequencyEnabled()); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(MATURITY)); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SEX)); + Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SIZE)); + Assert.assertTrue(sp1.isWeightEnabled()); + + SpeciesProtocol sp2 = protocol.getBenthos(1); + Assert.assertNotNull(sp2); + Assert.assertEquals(2, sp2.getSpeciesReferenceTaxonId(), 0); + Assert.assertNull(sp2.getSpeciesSurveyCode()); + Assert.assertNull(sp2.getLengthStepPmfmId()); + Assert.assertTrue(sp2.containsMandatorySampleCategoryId(AGE)); + Assert.assertTrue(sp2.isCalcifySampleEnabled()); + Assert.assertTrue(sp2.isCountIfNoFrequencyEnabled()); + Assert.assertFalse(sp2.containsMandatorySampleCategoryId(MATURITY)); + Assert.assertTrue(sp2.containsMandatorySampleCategoryId(SEX)); + Assert.assertFalse(sp2.containsMandatorySampleCategoryId(SIZE)); + Assert.assertTrue(sp2.isWeightEnabled()); + } + + @Test + public void exportProtocolBenthos() throws Exception { + + File file = new File(datadirectory, "exportProtocolBenthos.csv"); + + Files.createParentDirs(file); + + Map<String, Species> speciesMap = createSpecies(); + + TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); + protocol.setBenthos(Lists.<SpeciesProtocol>newArrayList()); + + SpeciesProtocol sp1 = TuttiBeanFactory.newSpeciesProtocol(); + sp1.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); + sp1.setId(21); + sp1.setSpeciesReferenceTaxonId(1); + sp1.setSpeciesSurveyCode("cruiseCode1"); + sp1.addMandatorySampleCategoryId(AGE); + sp1.addMandatorySampleCategoryId(SIZE); + sp1.addMandatorySampleCategoryId(MATURITY); + sp1.addMandatorySampleCategoryId(SEX); + sp1.setWeightEnabled(true); + sp1.setCountIfNoFrequencyEnabled(true); + sp1.setCalcifySampleEnabled(true); + sp1.setLengthStepPmfmId("2"); + + protocol.addBenthos(sp1); + + SpeciesProtocol sp2 = TuttiBeanFactory.newSpeciesProtocol(); + sp2.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); + sp2.setId(22); + sp2.setSpeciesReferenceTaxonId(2); + sp2.addMandatorySampleCategoryId(AGE); + sp2.removeMandatorySampleCategoryId(SIZE); + sp2.removeMandatorySampleCategoryId(MATURITY); + sp2.addMandatorySampleCategoryId(SEX); + sp2.setWeightEnabled(true); + sp2.setCalcifySampleEnabled(true); + sp2.setCountIfNoFrequencyEnabled(true); + sp2.setLengthStepPmfmId(null); + + protocol.addBenthos(sp2); + + Assert.assertFalse(file.exists()); + service.exportProtocolBenthos(file, + protocol.getBenthos(), + createCaracteristics(), + speciesMap); + + Assert.assertTrue(file.exists()); + + String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); + Assert.assertEquals(PROTOCOL_BENTHOS_FILE_CONTENT, exportFileToString); + } + + protected Map<String, Caracteristic> createCaracteristics() { + Map<String, Caracteristic> result = Maps.newTreeMap(); + for (int i = 1; i < 6; i++) { + Caracteristic c = TuttiBeanFactory.newCaracteristic(); + c.setId("" + i); + c.setParameterName("parameterName" + i); + c.setMatrixName("matrixName" + i); + c.setFractionName("fractionName" + i); + c.setMethodName("methodName" + i); + result.put(i + "", c); + } + return result; + } + + protected Map<String, Species> createSpecies() { + Map<String, Species> result = Maps.newTreeMap(); + for (int i = 1; i < 3; i++) { + Species c = TuttiBeanFactory.newSpecies(); + c.setId("" + i); + c.setReferenceTaxonId(i); + c.setName("speciesName" + i); + c.setRefTaxCode("speciesRefTaxCode" + i); + result.put(i + "", c); + } + return result; + } +} Deleted: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportServiceTest.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportServiceTest.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/protocol/TuttiProtocolImportExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,618 +0,0 @@ -package fr.ifremer.tutti.service.protocol; - -/* - * #%L - * Tutti :: Service - * $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.Charsets; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.io.Files; -import fr.ifremer.tutti.persistence.entities.TuttiBeanFactory; -import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; -import fr.ifremer.tutti.persistence.entities.referential.Species; -import fr.ifremer.tutti.service.ServiceDbResource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; - -import java.io.File; -import java.util.Map; - -/** - * @author tchemit <chemit@codelutin.com> - * @since 1.0 - */ -public class TuttiProtocolImportExportServiceTest { - - @ClassRule - public static final ServiceDbResource dbResource = - ServiceDbResource.writeDb("dbCGFS"); - - protected TuttiProtocolImportExportService service; - - public static final int VRAC_HORS_VRAC = 1428; - - public static final int SIZE = 198; - - public static final int SEX = 196; - - public static final int MATURITY = 174; - - public static final int AGE = 1430; - - public static final String PROTOCOL_FILE_CONTENT = - "id: 1\n" + - "name: protocolName\n" + - "benthos: \n" + - "- !SpeciesProtocol\n" + - " id: 21\n" + - " calcifySampleEnabled: true\n" + - " lengthStepPmfmId: 1394\n" + - " mandatorySampleCategoryId: \n" + - " - 174\n" + - " - 196\n" + - " speciesReferenceTaxonId: 11242\n" + - " speciesSurveyCode: cruiseCode1\n" + - " weightEnabled: true\n" + - "- !SpeciesProtocol\n" + - " id: 22\n" + - " calcifySampleEnabled: true\n" + - " countIfNoFrequencyEnabled: true\n" + - " lengthStepPmfmId: 323\n" + - " mandatorySampleCategoryId: \n" + - " - 1430\n" + - " - 174\n" + - " - 196\n" + - " - 198\n" + - " speciesReferenceTaxonId: 3835\n" + - " weightEnabled: true\n" + - "comment: Commentaire\n" + - "gearUseFeaturePmfmId: \n" + - "- 21\n" + - "- 22\n" + - "lengthClassesPmfmId: \n" + - "- 14\n" + - "- 18\n" + - "species: \n" + - "- !SpeciesProtocol\n" + - " id: 1\n" + - " calcifySampleEnabled: true\n" + - " lengthStepPmfmId: 1394\n" + - " mandatorySampleCategoryId: \n" + - " - 174\n" + - " - 196\n" + - " speciesReferenceTaxonId: 11242\n" + - " speciesSurveyCode: cruiseCode1\n" + - " weightEnabled: true\n" + - "- !SpeciesProtocol\n" + - " id: 2\n" + - " calcifySampleEnabled: true\n" + - " countIfNoFrequencyEnabled: true\n" + - " lengthStepPmfmId: 323\n" + - " mandatorySampleCategoryId: \n" + - " - 1430\n" + - " - 174\n" + - " - 196\n" + - " - 198\n" + - " speciesReferenceTaxonId: 3835\n" + - " weightEnabled: true\n" + - "version: 2\n" + - "vesselUseFeaturePmfmId: \n" + - "- 114\n" + - "- 228\n" + - "- 821"; - - public static final String PROTOCOL_CARACTERISTIC_FILE_CONTENT = - "pmfmId;pmfmType;pmfmParameterName;pmfmMatrixName;pmfmFractionName;pmfmMethodName\n" + - "1;LENGTH_STEP;parameterName1;matrixName1;fractionName1;methodName1;\n" + - "2;VESSEL_USE_FEATURE;parameterName2;matrixName2;fractionName2;methodName2;\n" + - "3;GEAR_USE_FEATURE;parameterName3;matrixName3;fractionName3;methodName3;"; - - public static final String ALL_CARACTERISTIC_FILE_CONTENT = - "pmfmId;pmfmType;pmfmParameterName;pmfmMatrixName;pmfmFractionName;pmfmMethodName\n" + - "1;;parameterName1;matrixName1;fractionName1;methodName1;\n" + - "2;;parameterName2;matrixName2;fractionName2;methodName2;\n" + - "3;;parameterName3;matrixName3;fractionName3;methodName3;\n" + - "4;;parameterName4;matrixName4;fractionName4;methodName4;\n" + - "5;;parameterName5;matrixName5;fractionName5;methodName5;"; - - public static final String PROTOCOL_SPECIES_FILE_CONTENT = - "speciesReferenceTaxonId;speciesRefTaxCode;speciesName;speciesSurveyCode;lengthStepPmfmId;lengthStepPmfmParameterName;lengthStepPmfmMatrixName;lengthStepPmfmFractionName;lengthStepPmfmMethodName;mandatorySampleCategoryId;weightEnabled;countIfNoFrequencyEnabled;calcifySampleEnabled\n" + - "1;speciesRefTaxCode1;speciesName1;cruiseCode1;2;parameterName2;matrixName2;fractionName2;methodName2;1430|198|174|196;Y;Y;Y;\n" + - "2;speciesRefTaxCode2;speciesName2;;;;;;;1430|196;Y;Y;Y;"; - - public static final String PROTOCOL_BENTHOS_FILE_CONTENT = - "speciesReferenceTaxonId;speciesRefTaxCode;speciesName;speciesSurveyCode;lengthStepPmfmId;lengthStepPmfmParameterName;lengthStepPmfmMatrixName;lengthStepPmfmFractionName;lengthStepPmfmMethodName;mandatorySampleCategoryId;weightEnabled;countIfNoFrequencyEnabled;calcifySampleEnabled\n" + - "1;speciesRefTaxCode1;speciesName1;cruiseCode1;2;parameterName2;matrixName2;fractionName2;methodName2;1430|198|174|196;Y;Y;Y;\n" + - "2;speciesRefTaxCode2;speciesName2;;;;;;;1430|196;Y;Y;Y;"; - - File datadirectory; - - @Before - public void setUp() throws Exception { - - dbResource.getServiceConfig().setCsvSeparator(';'); - - service = dbResource.getServiceContext().getService( - TuttiProtocolImportExportService.class); - - datadirectory = dbResource.getServiceConfig().getDataDirectory(); - } - - @Test - public void exportProtocol() throws Exception { - - File exportFile = new File(datadirectory, "exportProtocol.yaml"); - - Files.createParentDirs(exportFile); - - Assert.assertFalse(exportFile.exists()); - TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); - protocol.setVersion(2); - protocol.setId("1"); - protocol.setName("protocolName"); - protocol.setComment("Commentaire"); - protocol.setLengthClassesPmfmId(Lists.newArrayList("14", "18")); - protocol.setVesselUseFeaturePmfmId(Lists.newArrayList("114", "228", "821")); - protocol.setGearUseFeaturePmfmId(Lists.newArrayList("21", "22")); - - protocol.setSpecies(Lists.<SpeciesProtocol>newArrayList()); - SpeciesProtocol sp1 = TuttiBeanFactory.newSpeciesProtocol(); - sp1.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); - sp1.setId(1); - sp1.setSpeciesReferenceTaxonId(11242); - sp1.setSpeciesSurveyCode("cruiseCode1"); - sp1.setLengthStepPmfmId("1394"); - sp1.setCalcifySampleEnabled(true); - sp1.addMandatorySampleCategoryId(MATURITY); - sp1.addMandatorySampleCategoryId(SEX); - sp1.setWeightEnabled(true); - protocol.addSpecies(sp1); - - SpeciesProtocol sp2 = TuttiBeanFactory.newSpeciesProtocol(); - sp2.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); - sp2.setId(2); - sp2.setSpeciesReferenceTaxonId(3835); - sp2.setLengthStepPmfmId("323"); - sp2.addMandatorySampleCategoryId(AGE); - sp2.setCalcifySampleEnabled(true); - sp2.setCountIfNoFrequencyEnabled(true); - sp2.addMandatorySampleCategoryId(MATURITY); - sp2.addMandatorySampleCategoryId(SEX); - sp2.addMandatorySampleCategoryId(SIZE); - sp2.setWeightEnabled(true); - protocol.addSpecies(sp2); - - protocol.setBenthos(Lists.<SpeciesProtocol>newArrayList()); - SpeciesProtocol bp1 = TuttiBeanFactory.newSpeciesProtocol(); - bp1.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); - bp1.setId(21); - bp1.setSpeciesSurveyCode("cruiseCode1"); - bp1.setSpeciesReferenceTaxonId(11242); - bp1.setLengthStepPmfmId("1394"); - bp1.setCalcifySampleEnabled(true); - bp1.addMandatorySampleCategoryId(MATURITY); - bp1.addMandatorySampleCategoryId(SEX); - bp1.setWeightEnabled(true); - protocol.addBenthos(bp1); - - SpeciesProtocol bp2 = TuttiBeanFactory.newSpeciesProtocol(); - bp2.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); - bp2.setId(22); - bp2.setSpeciesReferenceTaxonId(3835); - bp2.setLengthStepPmfmId("323"); - bp2.addMandatorySampleCategoryId(AGE); - bp2.setCalcifySampleEnabled(true); - bp2.setCountIfNoFrequencyEnabled(true); - bp2.addMandatorySampleCategoryId(MATURITY); - bp2.addMandatorySampleCategoryId(SEX); - bp2.addMandatorySampleCategoryId(SIZE); - bp2.setWeightEnabled(true); - protocol.addBenthos(bp2); - - service.exportProtocol(protocol, exportFile); - Assert.assertTrue(exportFile.exists()); - - String exportFileToString = Files.toString(exportFile, Charsets.UTF_8).trim(); - Assert.assertEquals(PROTOCOL_FILE_CONTENT, exportFileToString); - } - - @Test - public void importProtocol() throws Exception { - - File importfile = new File(datadirectory, "importProtocol.yaml"); - - Files.createParentDirs(importfile); - - Files.write(PROTOCOL_FILE_CONTENT, importfile, Charsets.UTF_8); - - TuttiProtocol protocol = service.importProtocol(importfile); - - Assert.assertNotNull(protocol); - Assert.assertEquals("1", protocol.getId()); - Assert.assertEquals(2, protocol.getVersion(),0); - Assert.assertEquals("protocolName", protocol.getName()); - Assert.assertEquals("Commentaire", protocol.getComment()); - Assert.assertEquals(Lists.newArrayList("14", "18"), protocol.getLengthClassesPmfmId()); - Assert.assertEquals(Lists.newArrayList("114", "228", "821"), protocol.getVesselUseFeaturePmfmId()); - Assert.assertEquals(Lists.newArrayList("21", "22"), protocol.getGearUseFeaturePmfmId()); - - Assert.assertNotNull(protocol.getSpecies()); - Assert.assertEquals(2, protocol.sizeSpecies()); - SpeciesProtocol sp1 = protocol.getSpecies(0); - Assert.assertNotNull(sp1); - Assert.assertEquals(1, sp1.getIdAsInt(), 0); - Assert.assertEquals(11242, sp1.getSpeciesReferenceTaxonId(), 0); - Assert.assertEquals("cruiseCode1", sp1.getSpeciesSurveyCode()); - Assert.assertEquals("1394", sp1.getLengthStepPmfmId()); - Assert.assertFalse(sp1.containsMandatorySampleCategoryId(AGE)); - Assert.assertTrue(sp1.isCalcifySampleEnabled()); - Assert.assertFalse(sp1.isCountIfNoFrequencyEnabled()); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(MATURITY)); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SEX)); - Assert.assertFalse(sp1.containsMandatorySampleCategoryId(SIZE)); - Assert.assertTrue(sp1.isWeightEnabled()); - - SpeciesProtocol sp2 = protocol.getSpecies(1); - Assert.assertNotNull(sp2); - Assert.assertEquals(2, sp2.getIdAsInt(), 0); - Assert.assertEquals(3835, sp2.getSpeciesReferenceTaxonId(), 0); - Assert.assertEquals("323", sp2.getLengthStepPmfmId()); - Assert.assertTrue(sp2.containsMandatorySampleCategoryId(AGE)); - Assert.assertTrue(sp2.isCalcifySampleEnabled()); - Assert.assertTrue(sp2.isCountIfNoFrequencyEnabled()); - Assert.assertTrue(sp2.containsMandatorySampleCategoryId(MATURITY)); - Assert.assertTrue(sp2.containsMandatorySampleCategoryId(SEX)); - Assert.assertTrue(sp2.containsMandatorySampleCategoryId(SIZE)); - Assert.assertTrue(sp2.isWeightEnabled()); - - Assert.assertNotNull(protocol.getBenthos()); - Assert.assertEquals(2, protocol.sizeBenthos()); - SpeciesProtocol b1 = protocol.getBenthos(0); - Assert.assertNotNull(b1); - Assert.assertEquals(21, b1.getIdAsInt(), 0); - Assert.assertEquals(11242, b1.getSpeciesReferenceTaxonId(), 0); - Assert.assertEquals("cruiseCode1", b1.getSpeciesSurveyCode()); - Assert.assertEquals("1394", b1.getLengthStepPmfmId()); - Assert.assertFalse(b1.containsMandatorySampleCategoryId(AGE)); - Assert.assertTrue(b1.isCalcifySampleEnabled()); - Assert.assertFalse(b1.isCountIfNoFrequencyEnabled()); - Assert.assertTrue(b1.containsMandatorySampleCategoryId(MATURITY)); - Assert.assertTrue(b1.containsMandatorySampleCategoryId(SEX)); - Assert.assertFalse(b1.containsMandatorySampleCategoryId(SIZE)); - Assert.assertTrue(b1.isWeightEnabled()); - - SpeciesProtocol b2 = protocol.getBenthos(1); - Assert.assertNotNull(b2); - Assert.assertEquals(22, b2.getIdAsInt(), 0); - Assert.assertEquals(3835, b2.getSpeciesReferenceTaxonId(), 0); - Assert.assertEquals("323", b2.getLengthStepPmfmId()); - Assert.assertTrue(b2.containsMandatorySampleCategoryId(AGE)); - Assert.assertTrue(b2.isCalcifySampleEnabled()); - Assert.assertTrue(b2.isCountIfNoFrequencyEnabled()); - Assert.assertTrue(b2.containsMandatorySampleCategoryId(MATURITY)); - Assert.assertTrue(b2.containsMandatorySampleCategoryId(SEX)); - Assert.assertTrue(b2.containsMandatorySampleCategoryId(SIZE)); - Assert.assertTrue(b2.isWeightEnabled()); - } - - @Test - public void importProtocolCaracteristic() throws Exception { - - File file = new File(datadirectory, "importProtocolCaracteristic.csv"); - - Files.createParentDirs(file); - - Files.write(PROTOCOL_CARACTERISTIC_FILE_CONTENT, file, Charsets.UTF_8); - - TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); - Map<String, Caracteristic> caracteristicMap = createCaracteristics(); - - service.importProtocolCaracteristic(file, - protocol, - caracteristicMap); - - Assert.assertEquals(Lists.newArrayList("1"), - protocol.getLengthClassesPmfmId()); - Assert.assertEquals(Lists.newArrayList("2"), - protocol.getVesselUseFeaturePmfmId()); - Assert.assertEquals(Lists.newArrayList("3"), - protocol.getGearUseFeaturePmfmId()); - } - - @Test - public void exportProtocolCaracteristic() throws Exception { - - File file = new File(datadirectory, "exportProtocolCaracteristic.csv"); - - Files.createParentDirs(file); - - Map<String, Caracteristic> caracteristicMap = createCaracteristics(); - TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); - - protocol.setLengthClassesPmfmId(Lists.newArrayList("1")); - protocol.setVesselUseFeaturePmfmId(Lists.newArrayList("2")); - protocol.setGearUseFeaturePmfmId(Lists.newArrayList("3")); - - Assert.assertFalse(file.exists()); - service.exportProtocolCaracteristic(file, - protocol, - caracteristicMap); - - Assert.assertTrue(file.exists()); - - String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); - Assert.assertEquals(PROTOCOL_CARACTERISTIC_FILE_CONTENT, exportFileToString); - } - - @Test - public void exportAllCaracteristic() throws Exception { - - File file = new File(datadirectory, "exportAllCaracteristic.csv"); - - Files.createParentDirs(file); - - Map<String, Caracteristic> caracteristicMap = createCaracteristics(); - - Assert.assertFalse(file.exists()); - service.exportAllCaracteristic(file, caracteristicMap); - - Assert.assertTrue(file.exists()); - - String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); - Assert.assertEquals(ALL_CARACTERISTIC_FILE_CONTENT, exportFileToString); - } - - @Test - public void importProtocolSpecies() throws Exception { - - File file = new File(datadirectory, "importProtocolSpecies.csv"); - - Files.createParentDirs(file); - - Files.write(PROTOCOL_SPECIES_FILE_CONTENT, file, Charsets.UTF_8); - - TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); - Map<String, Species> speciesMap = createSpecies(); - Map<String, Caracteristic> caracteristicMap = createCaracteristics(); - - service.importProtocolSpecies(file, - protocol, - caracteristicMap, - speciesMap); - - Assert.assertEquals(2, protocol.sizeSpecies()); - - SpeciesProtocol sp1 = protocol.getSpecies().get(0); - Assert.assertNotNull(sp1); - Assert.assertEquals(1, sp1.getSpeciesReferenceTaxonId(), 0); - Assert.assertEquals("cruiseCode1", sp1.getSpeciesSurveyCode()); - Assert.assertEquals("2", sp1.getLengthStepPmfmId()); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(AGE)); - Assert.assertTrue(sp1.isCalcifySampleEnabled()); - Assert.assertTrue(sp1.isCountIfNoFrequencyEnabled()); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(MATURITY)); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SEX)); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SIZE)); - Assert.assertTrue(sp1.isWeightEnabled()); - - SpeciesProtocol sp2 = protocol.getSpecies().get(1); - Assert.assertNotNull(sp2); - Assert.assertEquals(2, sp2.getSpeciesReferenceTaxonId(), 0); - Assert.assertNull(sp2.getSpeciesSurveyCode()); - Assert.assertNull(sp2.getLengthStepPmfmId()); - Assert.assertTrue(sp2.containsMandatorySampleCategoryId(AGE)); - Assert.assertTrue(sp2.isCalcifySampleEnabled()); - Assert.assertTrue(sp2.isCountIfNoFrequencyEnabled()); - Assert.assertFalse(sp2.containsMandatorySampleCategoryId(MATURITY)); - Assert.assertTrue(sp2.containsMandatorySampleCategoryId(SEX)); - Assert.assertFalse(sp2.containsMandatorySampleCategoryId(SIZE)); - Assert.assertTrue(sp2.isWeightEnabled()); - } - - @Test - public void exportProtocolSpecies() throws Exception { - - File file = new File(datadirectory, "exportProtocolSpecies.csv"); - - Files.createParentDirs(file); - - Map<String, Species> speciesMap = createSpecies(); - - TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); - protocol.setSpecies(Lists.<SpeciesProtocol>newArrayList()); - - SpeciesProtocol sp1 = TuttiBeanFactory.newSpeciesProtocol(); - sp1.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); - sp1.setSpeciesReferenceTaxonId(1); - sp1.setSpeciesSurveyCode("cruiseCode1"); - sp1.addMandatorySampleCategoryId(AGE); - sp1.addMandatorySampleCategoryId(SIZE); - sp1.addMandatorySampleCategoryId(MATURITY); - sp1.addMandatorySampleCategoryId(SEX); - sp1.setWeightEnabled(true); - sp1.setCountIfNoFrequencyEnabled(true); - sp1.setCalcifySampleEnabled(true); - sp1.setLengthStepPmfmId("2"); - - protocol.addSpecies(sp1); - - SpeciesProtocol sp2 = TuttiBeanFactory.newSpeciesProtocol(); - sp2.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); - sp2.setSpeciesReferenceTaxonId(2); - sp2.addMandatorySampleCategoryId(AGE); - sp2.removeMandatorySampleCategoryId(SIZE); - sp2.removeMandatorySampleCategoryId(MATURITY); - sp2.addMandatorySampleCategoryId(SEX); - sp2.setWeightEnabled(true); - sp2.setCalcifySampleEnabled(true); - sp2.setCountIfNoFrequencyEnabled(true); - sp2.setLengthStepPmfmId(null); - - protocol.addSpecies(sp2); - - Assert.assertFalse(file.exists()); - service.exportProtocolSpecies(file, - protocol.getSpecies(), - createCaracteristics(), - speciesMap); - - Assert.assertTrue(file.exists()); - - String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); - Assert.assertEquals(PROTOCOL_SPECIES_FILE_CONTENT, exportFileToString); - } - - @Test - public void importProtocolBenthos() throws Exception { - - File file = new File(datadirectory, "importProtocolBenthos.csv"); - - Files.createParentDirs(file); - - Files.write(PROTOCOL_BENTHOS_FILE_CONTENT, file, Charsets.UTF_8); - - TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); - Map<String, Species> speciesMap = createSpecies(); - Map<String, Caracteristic> caracteristicMap = createCaracteristics(); - - service.importProtocolBenthos(file, - protocol, - caracteristicMap, - speciesMap); - - Assert.assertEquals(2, protocol.sizeBenthos()); - - SpeciesProtocol sp1 = protocol.getBenthos(0); - Assert.assertNotNull(sp1); - Assert.assertEquals(1, sp1.getSpeciesReferenceTaxonId(), 0); - Assert.assertEquals("cruiseCode1", sp1.getSpeciesSurveyCode()); - Assert.assertEquals("2", sp1.getLengthStepPmfmId()); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(AGE)); - Assert.assertTrue(sp1.isCalcifySampleEnabled()); - Assert.assertTrue(sp1.isCountIfNoFrequencyEnabled()); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(MATURITY)); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SEX)); - Assert.assertTrue(sp1.containsMandatorySampleCategoryId(SIZE)); - Assert.assertTrue(sp1.isWeightEnabled()); - - SpeciesProtocol sp2 = protocol.getBenthos(1); - Assert.assertNotNull(sp2); - Assert.assertEquals(2, sp2.getSpeciesReferenceTaxonId(), 0); - Assert.assertNull(sp2.getSpeciesSurveyCode()); - Assert.assertNull(sp2.getLengthStepPmfmId()); - Assert.assertTrue(sp2.containsMandatorySampleCategoryId(AGE)); - Assert.assertTrue(sp2.isCalcifySampleEnabled()); - Assert.assertTrue(sp2.isCountIfNoFrequencyEnabled()); - Assert.assertFalse(sp2.containsMandatorySampleCategoryId(MATURITY)); - Assert.assertTrue(sp2.containsMandatorySampleCategoryId(SEX)); - Assert.assertFalse(sp2.containsMandatorySampleCategoryId(SIZE)); - Assert.assertTrue(sp2.isWeightEnabled()); - } - - @Test - public void exportProtocolBenthos() throws Exception { - - File file = new File(datadirectory, "exportProtocolBenthos.csv"); - - Files.createParentDirs(file); - - Map<String, Species> speciesMap = createSpecies(); - - TuttiProtocol protocol = TuttiBeanFactory.newTuttiProtocol(); - protocol.setBenthos(Lists.<SpeciesProtocol>newArrayList()); - - SpeciesProtocol sp1 = TuttiBeanFactory.newSpeciesProtocol(); - sp1.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); - sp1.setId(21); - sp1.setSpeciesReferenceTaxonId(1); - sp1.setSpeciesSurveyCode("cruiseCode1"); - sp1.addMandatorySampleCategoryId(AGE); - sp1.addMandatorySampleCategoryId(SIZE); - sp1.addMandatorySampleCategoryId(MATURITY); - sp1.addMandatorySampleCategoryId(SEX); - sp1.setWeightEnabled(true); - sp1.setCountIfNoFrequencyEnabled(true); - sp1.setCalcifySampleEnabled(true); - sp1.setLengthStepPmfmId("2"); - - protocol.addBenthos(sp1); - - SpeciesProtocol sp2 = TuttiBeanFactory.newSpeciesProtocol(); - sp2.setMandatorySampleCategoryId(Lists.<Integer>newArrayList()); - sp2.setId(22); - sp2.setSpeciesReferenceTaxonId(2); - sp2.addMandatorySampleCategoryId(AGE); - sp2.removeMandatorySampleCategoryId(SIZE); - sp2.removeMandatorySampleCategoryId(MATURITY); - sp2.addMandatorySampleCategoryId(SEX); - sp2.setWeightEnabled(true); - sp2.setCalcifySampleEnabled(true); - sp2.setCountIfNoFrequencyEnabled(true); - sp2.setLengthStepPmfmId(null); - - protocol.addBenthos(sp2); - - Assert.assertFalse(file.exists()); - service.exportProtocolBenthos(file, - protocol.getBenthos(), - createCaracteristics(), - speciesMap); - - Assert.assertTrue(file.exists()); - - String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); - Assert.assertEquals(PROTOCOL_BENTHOS_FILE_CONTENT, exportFileToString); - } - - protected Map<String, Caracteristic> createCaracteristics() { - Map<String, Caracteristic> result = Maps.newTreeMap(); - for (int i = 1; i < 6; i++) { - Caracteristic c = TuttiBeanFactory.newCaracteristic(); - c.setId("" + i); - c.setParameterName("parameterName" + i); - c.setMatrixName("matrixName" + i); - c.setFractionName("fractionName" + i); - c.setMethodName("methodName" + i); - result.put(i + "", c); - } - return result; - } - - protected Map<String, Species> createSpecies() { - Map<String, Species> result = Maps.newTreeMap(); - for (int i = 1; i < 3; i++) { - Species c = TuttiBeanFactory.newSpecies(); - c.setId("" + i); - c.setReferenceTaxonId(i); - c.setName("speciesName" + i); - c.setRefTaxCode("speciesRefTaxCode" + i); - result.put(i + "", c); - } - return result; - } -} Copied: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/PupitriImportExportServiceTest.java (from rev 1246, trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportServiceTest.java) =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/PupitriImportExportServiceTest.java (rev 0) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/PupitriImportExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,112 @@ +package fr.ifremer.tutti.service.pupitri; + +/* + * #%L + * Tutti :: Service + * $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.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.CatchBatch; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.ServiceDbResource; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +/** + * @author tchemit <chemit@codelutin.com> + * @since 2.4 + */ +public class PupitriImportExportServiceTest { + + @ClassRule + public static final ServiceDbResource dbResource = + ServiceDbResource.writeDb("dbExport"); + + public static final String PROGRAM_ID = "CAM-TEST_ELEVATION"; + + public static final String CRUISE_ID = "100003"; + + public static final String OPERATION_1_ID = "100112"; + + public static final String OPERATION_2_ID = "100113"; + + public static final String OPERATION_3_ID = "100115"; + + protected PupitriImportExportService service; + + protected PersistenceService persistenceService; + + protected ServiceDbResource.DataContext dataContext; + + @Before + public void setUp() throws Exception { + + TuttiServiceContext serviceContext = dbResource.getServiceContext(); + + persistenceService = serviceContext.getService(PersistenceService.class); + + dbResource.openDataContext(); + + service = serviceContext.getService(PupitriImportExportService.class); + + dataContext = dbResource.loadContext(PROGRAM_ID, CRUISE_ID, 3, + OPERATION_2_ID, + OPERATION_1_ID, + OPERATION_3_ID); + } + + @Test + public void importPupitri() throws IOException { + + File trunk = dbResource.copyClassPathResource("pupitri/pupitri.tnk", "pupitri.tnk"); + File carroussel = dbResource.copyClassPathResource("pupitri/pupitri.car", "pupitri.car"); + + FishingOperation operation = dataContext.operations.get(1); + CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operation.getId()); + catchBatch.setFishingOperation(operation); + + BatchContainer<SpeciesBatch> rootSpeciesBatch = persistenceService.getRootSpeciesBatch(operation.getId(), null); + Assert.assertEquals(3, rootSpeciesBatch.sizeChildren()); + int nbAdded = service.importPupitri(trunk, carroussel, operation, catchBatch); + Assert.assertEquals(6, nbAdded); + BatchContainer<SpeciesBatch> rootSpeciesBatchAfter = persistenceService.getRootSpeciesBatch(operation.getId(), null); + Assert.assertEquals(18, rootSpeciesBatchAfter.sizeChildren()); + + int index = 0; + for (SpeciesBatch speciesBatch : rootSpeciesBatchAfter.getChildren()) { + + int nbChildren = 0; + if (index == 11) { + nbChildren = 2; + } + Assert.assertEquals("SpeciesBatch at index " + (index++) + " should have " + nbChildren + " but had " + speciesBatch.sizeChildBatchs(), nbChildren, speciesBatch.sizeChildBatchs()); + } + } +} Deleted: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportServiceTest.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportServiceTest.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/pupitri/TuttiPupitriImportExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,112 +0,0 @@ -package fr.ifremer.tutti.service.pupitri; - -/* - * #%L - * Tutti :: Service - * $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.entities.data.BatchContainer; -import fr.ifremer.tutti.persistence.entities.data.CatchBatch; -import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.ServiceDbResource; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; - -/** - * @author tchemit <chemit@codelutin.com> - * @since 2.4 - */ -public class TuttiPupitriImportExportServiceTest { - - @ClassRule - public static final ServiceDbResource dbResource = - ServiceDbResource.writeDb("dbExport"); - - public static final String PROGRAM_ID = "CAM-TEST_ELEVATION"; - - public static final String CRUISE_ID = "100003"; - - public static final String OPERATION_1_ID = "100112"; - - public static final String OPERATION_2_ID = "100113"; - - public static final String OPERATION_3_ID = "100115"; - - protected TuttiPupitriImportExportService service; - - protected PersistenceService persistenceService; - - protected ServiceDbResource.DataContext dataContext; - - @Before - public void setUp() throws Exception { - - TuttiServiceContext serviceContext = dbResource.getServiceContext(); - - persistenceService = serviceContext.getService(PersistenceService.class); - - dbResource.openDataContext(); - - service = serviceContext.getService(TuttiPupitriImportExportService.class); - - dataContext = dbResource.loadContext(PROGRAM_ID, CRUISE_ID, 3, - OPERATION_2_ID, - OPERATION_1_ID, - OPERATION_3_ID); - } - - @Test - public void importPupitri() throws IOException { - - File trunk = dbResource.copyClassPathResource("pupitri/pupitri.tnk", "pupitri.tnk"); - File carroussel = dbResource.copyClassPathResource("pupitri/pupitri.car", "pupitri.car"); - - FishingOperation operation = dataContext.operations.get(1); - CatchBatch catchBatch = persistenceService.getCatchBatchFromFishingOperation(operation.getId()); - catchBatch.setFishingOperation(operation); - - BatchContainer<SpeciesBatch> rootSpeciesBatch = persistenceService.getRootSpeciesBatch(operation.getId(), null); - Assert.assertEquals(3, rootSpeciesBatch.sizeChildren()); - int nbAdded = service.importPupitri(trunk, carroussel, operation, catchBatch); - Assert.assertEquals(6, nbAdded); - BatchContainer<SpeciesBatch> rootSpeciesBatchAfter = persistenceService.getRootSpeciesBatch(operation.getId(), null); - Assert.assertEquals(18, rootSpeciesBatchAfter.sizeChildren()); - - int index = 0; - for (SpeciesBatch speciesBatch : rootSpeciesBatchAfter.getChildren()) { - - int nbChildren = 0; - if (index == 11) { - nbChildren = 2; - } - Assert.assertEquals("SpeciesBatch at index " + (index++) + " should have " + nbChildren + " but had " + speciesBatch.sizeChildBatchs(), nbChildren, speciesBatch.sizeChildBatchs()); - } - } -} Copied: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/ReferentialImportExportServiceTest.java (from rev 1246, trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportServiceTest.java) =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/ReferentialImportExportServiceTest.java (rev 0) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/ReferentialImportExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,287 @@ +package fr.ifremer.tutti.service.referential; + +/* + * #%L + * Tutti :: Service + * $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.Charsets; +import com.google.common.io.Files; +import fr.ifremer.tutti.TuttiTechnicalException; +import fr.ifremer.tutti.persistence.entities.referential.Gear; +import fr.ifremer.tutti.persistence.entities.referential.Person; +import fr.ifremer.tutti.persistence.entities.referential.Species; +import fr.ifremer.tutti.persistence.entities.referential.Vessel; +import fr.ifremer.tutti.service.ServiceDbResource; +import fr.ifremer.tutti.service.TuttiServiceContext; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +/** + * @author tchemit <chemit@codelutin.com> + * @since 1.0 + */ +public class ReferentialImportExportServiceTest { + + @ClassRule + public static final ServiceDbResource dbResource = + ServiceDbResource.writeDb("dbCGFS"); + + protected File dataDirectory; + + public static final String SPECIES_FILE_CONTENT = + "name\n" + + "Temporary Species name 1;\n" + + "Temporary Species name 2;\n" + + "Temporary Species name 3;"; + + public static final String GEAR_FILE_CONTENT = + "name;label;scientificGear\n" + + "Gear fishing name 1;Gear fishing label 1;N;\n" + + "Gear fishing name 2;Gear fishing label 2;N;\n" + + "Gear scientific name 3;Gear scientific label 3;Y;\n" + + "Gear scientific name 4;Gear scientific label 4;Y;"; + + public static final String PERSON_FILE_CONTENT = + "firstName;lastName\n" + + "First name 1;Last name 1;\n" + + "First name 2;Last name 2;\n" + + "First name 3;Last name 3;"; + + public static final String VESSEL_FILE_CONTENT = + "name;internationalRegistrationCode;scientificVessel\n" + + "Temporary fishing vessel name 1;International registration code F1;N;\n" + + "Temporary fishing vessel name 2;International registration code F2;N;\n" + + "Temporary scientific vessel name 3;International registration code S3;Y;\n" + + "Temporary scientific vessel name 4;International registration code S4;Y;"; + + public static final String DUPLICATE_VESSEL_FILE_CONTENT = + "name;internationalRegistrationCode;scientificVessel\n" + + "Temporary fishing vessel name 1;International registration code F1;N;\n" + + "Temporary fishing vessel name 1;International registration code F1;N;\n" + + "Temporary fishing vessel name 2;International registration code F2;N;\n" + + "Temporary scientific vessel name 3;International registration code S3;Y;\n" + + "Temporary scientific vessel name 4;International registration code S4;Y;"; + + protected ReferentialImportExportService service; + + @Before + public void setUp() throws Exception { + + dataDirectory = dbResource.getServiceConfig().getDataDirectory(); + + TuttiServiceContext serviceContext = dbResource.getServiceContext(); + + serviceContext.getConfig().setCsvSeparator(';'); + + service = serviceContext.getService(ReferentialImportExportService.class); + } + + @Test + public void importTemporarySpecies() throws Exception { + + File file = new File(dataDirectory, "importSpecies.csv"); + + Files.createParentDirs(file); + + Files.write(SPECIES_FILE_CONTENT, file, Charsets.UTF_8); + + List<Species> result = service.importTemporarySpecies(file); + + Assert.assertNotNull(result); + Assert.assertEquals(3, result.size()); + for (int i = 1; i <= 3; i++) { + Species actual = result.get(i - 1); + Assert.assertNotNull(actual); + Assert.assertEquals("-" + i, actual.getId()); + Assert.assertEquals("Temporary Species name " + i, actual.getName()); + } + // try to reimport them + try { + service.importTemporarySpecies(file); + Assert.fail(); + } catch (TuttiTechnicalException e) { + Assert.assertTrue(true); + } + } + + @Test + public void importTemporaryVessel() throws Exception { + File file = new File(dataDirectory, "importVessel.csv"); + + Files.createParentDirs(file); + + Files.write(VESSEL_FILE_CONTENT, file, Charsets.UTF_8); + + List<Vessel> result = service.importTemporaryVessel(file); + + Assert.assertNotNull(result); + Assert.assertEquals(4, result.size()); + for (int i = 1; i <= 2; i++) { + Vessel actual = result.get(i - 1); + Assert.assertNotNull(actual); + Assert.assertEquals("#TEMP¿" + actual.getInternationalRegistrationCode(), actual.getId()); + Assert.assertEquals("Temporary fishing vessel name " + i, actual.getName()); + Assert.assertEquals("International registration code F" + i, actual.getInternationalRegistrationCode()); + Assert.assertFalse(actual.isScientificVessel()); + } + for (int i = 3; i <= 4; i++) { + Vessel actual = result.get(i - 1); + Assert.assertNotNull(actual); + Assert.assertEquals("#TEMP¿" + actual.getInternationalRegistrationCode(), actual.getId()); + Assert.assertEquals("Temporary scientific vessel name " + i, actual.getName()); + Assert.assertEquals("International registration code S" + i, actual.getInternationalRegistrationCode()); + Assert.assertTrue(actual.isScientificVessel()); + } + // try to reimport them + try { + service.importTemporaryVessel(file); + Assert.fail(); + } catch (TuttiTechnicalException e) { + Assert.assertTrue(true); + } + } + + @Test + public void importDuplicateTemporaryVessel() throws Exception { + File file = new File(dataDirectory, "importVessel.csv"); + + Files.createParentDirs(file); + + Files.write(DUPLICATE_VESSEL_FILE_CONTENT, file, Charsets.UTF_8); + + try { + service.importTemporaryVessel(file); + Assert.fail(); + } catch (TuttiTechnicalException e) { + // good duplicate vessel + } + } + + @Test + public void importTemporaryPerson() throws Exception { + File file = new File(dataDirectory, "importPerson.csv"); + + Files.createParentDirs(file); + + Files.write(PERSON_FILE_CONTENT, file, Charsets.UTF_8); + + List<Person> result = service.importTemporaryPerson(file); + + Assert.assertNotNull(result); + Assert.assertEquals(3, result.size()); + for (int i = 1; i <= 3; i++) { + Person actual = result.get(i - 1); + Assert.assertNotNull(actual); + Assert.assertEquals("-" + i, actual.getId()); + Assert.assertEquals("First name " + i, actual.getFirstName()); + Assert.assertEquals("Last name " + i, actual.getLastName()); + } + } + + @Test + public void importTemporaryGear() throws Exception { + File file = new File(dataDirectory, "importGear.csv"); + + Files.createParentDirs(file); + + Files.write(GEAR_FILE_CONTENT, file, Charsets.UTF_8); + + List<Gear> result = service.importTemporaryGear(file); + + Assert.assertNotNull(result); + Assert.assertEquals(4, result.size()); + for (int i = 1; i <= 2; i++) { + Gear actual = result.get(i - 1); + Assert.assertNotNull(actual); + Assert.assertTrue(actual.getId().startsWith("-")); + Assert.assertEquals("Gear fishing name " + i, actual.getName()); + Assert.assertEquals("Gear fishing label " + i, actual.getLabel()); + Assert.assertFalse(actual.isScientificGear()); + } + for (int i = 3; i <= 4; i++) { + Gear actual = result.get(i - 1); + Assert.assertNotNull(actual); + Assert.assertTrue(actual.getId().startsWith("-")); + Assert.assertEquals("Gear scientific name " + i, actual.getName()); + Assert.assertEquals("Gear scientific label " + i, actual.getLabel()); + Assert.assertTrue(actual.isScientificGear()); + } + } + + @Test + public void exportTemporarySpeciesExample() throws Exception { + + File file = new File(dataDirectory, "exportSpecies.csv"); + + Assert.assertFalse(file.exists()); + service.exportTemporarySpeciesExample(file); + Assert.assertTrue(file.exists()); + + String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); + Assert.assertEquals(SPECIES_FILE_CONTENT, exportFileToString); + } + + @Test + public void exportTemporaryVesselExample() throws Exception { + File file = new File(dataDirectory, "exportVessel.csv"); + + Assert.assertFalse(file.exists()); + service.exportTemporaryVesselExample(file); + Assert.assertTrue(file.exists()); + + String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); + Assert.assertEquals(VESSEL_FILE_CONTENT, exportFileToString); + } + + @Test + public void exportTemporaryPersonExample() throws Exception { + + File file = new File(dataDirectory, "exportPerson.csv"); + + Assert.assertFalse(file.exists()); + service.exportTemporaryPersonExample(file); + Assert.assertTrue(file.exists()); + + String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); + Assert.assertEquals(PERSON_FILE_CONTENT, exportFileToString); + } + + @Test + public void exportTemporaryGearExample() throws Exception { + + File file = new File(dataDirectory, "exportGear.csv"); + + Assert.assertFalse(file.exists()); + service.exportTemporaryGearExample(file); + Assert.assertTrue(file.exists()); + + String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); + Assert.assertEquals(GEAR_FILE_CONTENT, exportFileToString); + } + +} Deleted: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportServiceTest.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportServiceTest.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/referential/TuttiReferentialImportExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,287 +0,0 @@ -package fr.ifremer.tutti.service.referential; - -/* - * #%L - * Tutti :: Service - * $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.Charsets; -import com.google.common.io.Files; -import fr.ifremer.tutti.TuttiTechnicalException; -import fr.ifremer.tutti.persistence.entities.referential.Gear; -import fr.ifremer.tutti.persistence.entities.referential.Person; -import fr.ifremer.tutti.persistence.entities.referential.Species; -import fr.ifremer.tutti.persistence.entities.referential.Vessel; -import fr.ifremer.tutti.service.ServiceDbResource; -import fr.ifremer.tutti.service.TuttiServiceContext; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; - -import java.io.File; -import java.util.List; - -/** - * @author tchemit <chemit@codelutin.com> - * @since 1.0 - */ -public class TuttiReferentialImportExportServiceTest { - - @ClassRule - public static final ServiceDbResource dbResource = - ServiceDbResource.writeDb("dbCGFS"); - - protected File dataDirectory; - - public static final String SPECIES_FILE_CONTENT = - "name\n" + - "Temporary Species name 1;\n" + - "Temporary Species name 2;\n" + - "Temporary Species name 3;"; - - public static final String GEAR_FILE_CONTENT = - "name;label;scientificGear\n" + - "Gear fishing name 1;Gear fishing label 1;N;\n" + - "Gear fishing name 2;Gear fishing label 2;N;\n" + - "Gear scientific name 3;Gear scientific label 3;Y;\n" + - "Gear scientific name 4;Gear scientific label 4;Y;"; - - public static final String PERSON_FILE_CONTENT = - "firstName;lastName\n" + - "First name 1;Last name 1;\n" + - "First name 2;Last name 2;\n" + - "First name 3;Last name 3;"; - - public static final String VESSEL_FILE_CONTENT = - "name;internationalRegistrationCode;scientificVessel\n" + - "Temporary fishing vessel name 1;International registration code F1;N;\n" + - "Temporary fishing vessel name 2;International registration code F2;N;\n" + - "Temporary scientific vessel name 3;International registration code S3;Y;\n" + - "Temporary scientific vessel name 4;International registration code S4;Y;"; - - public static final String DUPLICATE_VESSEL_FILE_CONTENT = - "name;internationalRegistrationCode;scientificVessel\n" + - "Temporary fishing vessel name 1;International registration code F1;N;\n" + - "Temporary fishing vessel name 1;International registration code F1;N;\n" + - "Temporary fishing vessel name 2;International registration code F2;N;\n" + - "Temporary scientific vessel name 3;International registration code S3;Y;\n" + - "Temporary scientific vessel name 4;International registration code S4;Y;"; - - protected TuttiReferentialImportExportService service; - - @Before - public void setUp() throws Exception { - - dataDirectory = dbResource.getServiceConfig().getDataDirectory(); - - TuttiServiceContext serviceContext = dbResource.getServiceContext(); - - serviceContext.getConfig().setCsvSeparator(';'); - - service = serviceContext.getService(TuttiReferentialImportExportService.class); - } - - @Test - public void importTemporarySpecies() throws Exception { - - File file = new File(dataDirectory, "importSpecies.csv"); - - Files.createParentDirs(file); - - Files.write(SPECIES_FILE_CONTENT, file, Charsets.UTF_8); - - List<Species> result = service.importTemporarySpecies(file); - - Assert.assertNotNull(result); - Assert.assertEquals(3, result.size()); - for (int i = 1; i <= 3; i++) { - Species actual = result.get(i - 1); - Assert.assertNotNull(actual); - Assert.assertEquals("-" + i, actual.getId()); - Assert.assertEquals("Temporary Species name " + i, actual.getName()); - } - // try to reimport them - try { - service.importTemporarySpecies(file); - Assert.fail(); - } catch (TuttiTechnicalException e) { - Assert.assertTrue(true); - } - } - - @Test - public void importTemporaryVessel() throws Exception { - File file = new File(dataDirectory, "importVessel.csv"); - - Files.createParentDirs(file); - - Files.write(VESSEL_FILE_CONTENT, file, Charsets.UTF_8); - - List<Vessel> result = service.importTemporaryVessel(file); - - Assert.assertNotNull(result); - Assert.assertEquals(4, result.size()); - for (int i = 1; i <= 2; i++) { - Vessel actual = result.get(i - 1); - Assert.assertNotNull(actual); - Assert.assertEquals("#TEMP¿" + actual.getInternationalRegistrationCode(), actual.getId()); - Assert.assertEquals("Temporary fishing vessel name " + i, actual.getName()); - Assert.assertEquals("International registration code F" + i, actual.getInternationalRegistrationCode()); - Assert.assertFalse(actual.isScientificVessel()); - } - for (int i = 3; i <= 4; i++) { - Vessel actual = result.get(i - 1); - Assert.assertNotNull(actual); - Assert.assertEquals("#TEMP¿" + actual.getInternationalRegistrationCode(), actual.getId()); - Assert.assertEquals("Temporary scientific vessel name " + i, actual.getName()); - Assert.assertEquals("International registration code S" + i, actual.getInternationalRegistrationCode()); - Assert.assertTrue(actual.isScientificVessel()); - } - // try to reimport them - try { - service.importTemporaryVessel(file); - Assert.fail(); - } catch (TuttiTechnicalException e) { - Assert.assertTrue(true); - } - } - - @Test - public void importDuplicateTemporaryVessel() throws Exception { - File file = new File(dataDirectory, "importVessel.csv"); - - Files.createParentDirs(file); - - Files.write(DUPLICATE_VESSEL_FILE_CONTENT, file, Charsets.UTF_8); - - try { - service.importTemporaryVessel(file); - Assert.fail(); - } catch (TuttiTechnicalException e) { - // good duplicate vessel - } - } - - @Test - public void importTemporaryPerson() throws Exception { - File file = new File(dataDirectory, "importPerson.csv"); - - Files.createParentDirs(file); - - Files.write(PERSON_FILE_CONTENT, file, Charsets.UTF_8); - - List<Person> result = service.importTemporaryPerson(file); - - Assert.assertNotNull(result); - Assert.assertEquals(3, result.size()); - for (int i = 1; i <= 3; i++) { - Person actual = result.get(i - 1); - Assert.assertNotNull(actual); - Assert.assertEquals("-" + i, actual.getId()); - Assert.assertEquals("First name " + i, actual.getFirstName()); - Assert.assertEquals("Last name " + i, actual.getLastName()); - } - } - - @Test - public void importTemporaryGear() throws Exception { - File file = new File(dataDirectory, "importGear.csv"); - - Files.createParentDirs(file); - - Files.write(GEAR_FILE_CONTENT, file, Charsets.UTF_8); - - List<Gear> result = service.importTemporaryGear(file); - - Assert.assertNotNull(result); - Assert.assertEquals(4, result.size()); - for (int i = 1; i <= 2; i++) { - Gear actual = result.get(i - 1); - Assert.assertNotNull(actual); - Assert.assertTrue(actual.getId().startsWith("-")); - Assert.assertEquals("Gear fishing name " + i, actual.getName()); - Assert.assertEquals("Gear fishing label " + i, actual.getLabel()); - Assert.assertFalse(actual.isScientificGear()); - } - for (int i = 3; i <= 4; i++) { - Gear actual = result.get(i - 1); - Assert.assertNotNull(actual); - Assert.assertTrue(actual.getId().startsWith("-")); - Assert.assertEquals("Gear scientific name " + i, actual.getName()); - Assert.assertEquals("Gear scientific label " + i, actual.getLabel()); - Assert.assertTrue(actual.isScientificGear()); - } - } - - @Test - public void exportTemporarySpeciesExample() throws Exception { - - File file = new File(dataDirectory, "exportSpecies.csv"); - - Assert.assertFalse(file.exists()); - service.exportTemporarySpeciesExample(file); - Assert.assertTrue(file.exists()); - - String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); - Assert.assertEquals(SPECIES_FILE_CONTENT, exportFileToString); - } - - @Test - public void exportTemporaryVesselExample() throws Exception { - File file = new File(dataDirectory, "exportVessel.csv"); - - Assert.assertFalse(file.exists()); - service.exportTemporaryVesselExample(file); - Assert.assertTrue(file.exists()); - - String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); - Assert.assertEquals(VESSEL_FILE_CONTENT, exportFileToString); - } - - @Test - public void exportTemporaryPersonExample() throws Exception { - - File file = new File(dataDirectory, "exportPerson.csv"); - - Assert.assertFalse(file.exists()); - service.exportTemporaryPersonExample(file); - Assert.assertTrue(file.exists()); - - String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); - Assert.assertEquals(PERSON_FILE_CONTENT, exportFileToString); - } - - @Test - public void exportTemporaryGearExample() throws Exception { - - File file = new File(dataDirectory, "exportGear.csv"); - - Assert.assertFalse(file.exists()); - service.exportTemporaryGearExample(file); - Assert.assertTrue(file.exists()); - - String exportFileToString = Files.toString(file, Charsets.UTF_8).trim(); - Assert.assertEquals(GEAR_FILE_CONTENT, exportFileToString); - } - -} Copied: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/CatchesSumatraExportServiceTest.java (from rev 1246, trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportServiceTest.java) =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/CatchesSumatraExportServiceTest.java (rev 0) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/CatchesSumatraExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,111 @@ +package fr.ifremer.tutti.service.sumatra; + +/* + * #%L + * Tutti :: Service + * $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.service.ServiceDbResource; +import fr.ifremer.tutti.service.TuttiServiceContext; +import fr.ifremer.tutti.service.catches.TuttiWeightComputingException; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import java.io.File; + +/** + * @author tchemit <chemit@codelutin.com> + * @since 2.4 + */ +public class CatchesSumatraExportServiceTest { + + @ClassRule + public static final ServiceDbResource dbResource = + ServiceDbResource.readDb("dbExport"); + + public static final String PROGRAM_ID = "CAM-TEST_ELEVATION"; + + public static final String CRUISE_BAD_ID = "100003"; + + public static final String CRUISE_ID = "100004"; + + public static final String OPERATION_1_ID = "100116"; + + public static final String OPERATION_BAD_1_ID = "100112"; + + public static final String OPERATION_BAD_2_ID = "100113"; + + public static final String OPERATION_BAD_3_ID = "100115"; + + public static final String EXPORT_CONTENT = + "Station;Espèce;Total;NbIndividus\n" + + "A;Chama magna;100.0;40;\n" + + "A;Echinogammarus;100.0;416;\n" + + "A;Brissopsis atlantica;100.0;94;"; + + protected CatchesSumatraExportService service; + + protected ServiceDbResource.DataContext dataContext; + + protected File dataDirectory; + + @Before + public void setUp() throws Exception { + + dataDirectory = dbResource.getServiceConfig().getDataDirectory(); + + TuttiServiceContext serviceContext = dbResource.getServiceContext(); + + dbResource.openDataContext(); + + service = serviceContext.getService(CatchesSumatraExportService.class); + } + + @Test(expected = TuttiWeightComputingException.class) + public void testExportCruiseForSumatraBadCruise() throws Exception { + + dataContext = dbResource.loadContext(PROGRAM_ID, CRUISE_BAD_ID, 3, + OPERATION_BAD_2_ID, + OPERATION_BAD_1_ID, + OPERATION_BAD_3_ID); + + File exportFile = new File(dataDirectory, "exportSumatra.csv"); + + service.exportCruiseForSumatra(exportFile, CRUISE_BAD_ID); + } + + @Test + public void testExportCruiseForSumatra() throws Exception { + + dataContext = dbResource.loadContext(PROGRAM_ID, CRUISE_ID, 1, + OPERATION_1_ID); + + File exportFile = new File(dataDirectory, "exportSumatra.csv"); + + service.exportCruiseForSumatra(exportFile, CRUISE_ID); + + ServiceDbResource.assertFileContent("Sumatra export file:\n", + exportFile, + EXPORT_CONTENT); + } +} Deleted: trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportServiceTest.java =================================================================== --- trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportServiceTest.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-service/src/test/java/fr/ifremer/tutti/service/sumatra/TuttiCatchesSumatraExportServiceTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,111 +0,0 @@ -package fr.ifremer.tutti.service.sumatra; - -/* - * #%L - * Tutti :: Service - * $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.service.ServiceDbResource; -import fr.ifremer.tutti.service.TuttiServiceContext; -import fr.ifremer.tutti.service.catches.TuttiWeightComputingException; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; - -import java.io.File; - -/** - * @author tchemit <chemit@codelutin.com> - * @since 2.4 - */ -public class TuttiCatchesSumatraExportServiceTest { - - @ClassRule - public static final ServiceDbResource dbResource = - ServiceDbResource.readDb("dbExport"); - - public static final String PROGRAM_ID = "CAM-TEST_ELEVATION"; - - public static final String CRUISE_BAD_ID = "100003"; - - public static final String CRUISE_ID = "100004"; - - public static final String OPERATION_1_ID = "100116"; - - public static final String OPERATION_BAD_1_ID = "100112"; - - public static final String OPERATION_BAD_2_ID = "100113"; - - public static final String OPERATION_BAD_3_ID = "100115"; - - public static final String EXPORT_CONTENT = - "Station;Espèce;Total;NbIndividus\n" + - "A;Chama magna;100.0;40;\n" + - "A;Echinogammarus;100.0;416;\n" + - "A;Brissopsis atlantica;100.0;94;"; - - protected TuttiCatchesSumatraExportService service; - - protected ServiceDbResource.DataContext dataContext; - - protected File dataDirectory; - - @Before - public void setUp() throws Exception { - - dataDirectory = dbResource.getServiceConfig().getDataDirectory(); - - TuttiServiceContext serviceContext = dbResource.getServiceContext(); - - dbResource.openDataContext(); - - service = serviceContext.getService(TuttiCatchesSumatraExportService.class); - } - - @Test(expected = TuttiWeightComputingException.class) - public void testExportCruiseForSumatraBadCruise() throws Exception { - - dataContext = dbResource.loadContext(PROGRAM_ID, CRUISE_BAD_ID, 3, - OPERATION_BAD_2_ID, - OPERATION_BAD_1_ID, - OPERATION_BAD_3_ID); - - File exportFile = new File(dataDirectory, "exportSumatra.csv"); - - service.exportCruiseForSumatra(exportFile, CRUISE_BAD_ID); - } - - @Test - public void testExportCruiseForSumatra() throws Exception { - - dataContext = dbResource.loadContext(PROGRAM_ID, CRUISE_ID, 1, - OPERATION_1_ID); - - File exportFile = new File(dataDirectory, "exportSumatra.csv"); - - service.exportCruiseForSumatra(exportFile, CRUISE_ID); - - ServiceDbResource.assertFileContent("Sumatra export file:\n", - exportFile, - EXPORT_CONTENT); - } -} Modified: trunk/tutti-ui-swing/src/main/filtered-resources/tutti-help-en.properties =================================================================== --- trunk/tutti-ui-swing/src/main/filtered-resources/tutti-help-en.properties 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/filtered-resources/tutti-help-en.properties 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,5 +1,5 @@ #Generated by org.nuiton.jaxx.plugin.GenerateHelpIdsMojo -#Fri Sep 27 10:49:26 CEST 2013 +#Sat Sep 28 07:21:51 CEST 2013 tutti.config.help=config.html tutti.createAccidentalBatch.action.cancel.help=editFishingOperation.html\#captureCapturesAccidentellesActions tutti.createAccidentalBatch.action.saveAndClose.help=editFishingOperation.html\#captureCapturesAccidentellesActions @@ -111,6 +111,7 @@ tutti.editBenthosFrequencies.field.totalWeight.help=editFishingOperation.html\#captureBenthosFields tutti.editBenthosFrequencies.help=editFishingOperation.html\#captureBenthos tutti.editCatchBatch.action.cancelEditCatchBatch.help=editFishingOperation.html\#captureResumeActions +tutti.editCatchBatch.action.cleanWeights.help= tutti.editCatchBatch.action.computeWeights.help=editFishingOperation.html\#captureResumeActions tutti.editCatchBatch.action.importPupitri.help=editFishingOperation.html\#captureResumeActions tutti.editCatchBatch.action.saveCatchBatch.help=editFishingOperation.html\#captureResumeActions Modified: trunk/tutti-ui-swing/src/main/filtered-resources/tutti-help-fr.properties =================================================================== --- trunk/tutti-ui-swing/src/main/filtered-resources/tutti-help-fr.properties 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/filtered-resources/tutti-help-fr.properties 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,5 +1,5 @@ #Generated by org.nuiton.jaxx.plugin.GenerateHelpIdsMojo -#Fri Sep 27 10:49:26 CEST 2013 +#Sat Sep 28 07:21:51 CEST 2013 tutti.config.help=config.html tutti.createAccidentalBatch.action.cancel.help=editFishingOperation.html\#captureCapturesAccidentellesActions tutti.createAccidentalBatch.action.saveAndClose.help=editFishingOperation.html\#captureCapturesAccidentellesActions @@ -111,6 +111,7 @@ tutti.editBenthosFrequencies.field.totalWeight.help=editFishingOperation.html\#captureBenthosFields tutti.editBenthosFrequencies.help=editFishingOperation.html\#captureBenthos tutti.editCatchBatch.action.cancelEditCatchBatch.help=editFishingOperation.html\#captureResumeActions +tutti.editCatchBatch.action.cleanWeights.help= tutti.editCatchBatch.action.computeWeights.help=editFishingOperation.html\#captureResumeActions tutti.editCatchBatch.action.importPupitri.help=editFishingOperation.html\#captureResumeActions tutti.editCatchBatch.action.saveCatchBatch.help=editFishingOperation.html\#captureResumeActions Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUIContext.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUIContext.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUIContext.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -39,16 +39,17 @@ import fr.ifremer.tutti.service.TuttiServiceContext; import fr.ifremer.tutti.service.ValidationService; import fr.ifremer.tutti.service.catches.ExportCatchesReportService; -import fr.ifremer.tutti.service.catches.TuttiWeightComputingService; import fr.ifremer.tutti.service.catches.ValidateCruiseOperationsService; -import fr.ifremer.tutti.service.catches.multipost.TuttiMultiPostExportService; -import fr.ifremer.tutti.service.catches.multipost.TuttiMultiPostImportService; +import fr.ifremer.tutti.service.catches.WeightCleaningService; +import fr.ifremer.tutti.service.catches.WeightComputingService; +import fr.ifremer.tutti.service.catches.multipost.MultiPostExportService; +import fr.ifremer.tutti.service.catches.multipost.MultiPostImportService; import fr.ifremer.tutti.service.export.TuttiExportService; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; -import fr.ifremer.tutti.service.pupitri.TuttiPupitriImportExportService; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; +import fr.ifremer.tutti.service.pupitri.PupitriImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.service.referential.TuttiReferentialSynchronizeService; -import fr.ifremer.tutti.service.sumatra.TuttiCatchesSumatraExportService; +import fr.ifremer.tutti.service.sumatra.CatchesSumatraExportService; import fr.ifremer.tutti.ui.swing.config.TuttiApplicationConfig; import fr.ifremer.tutti.ui.swing.content.MainUI; import fr.ifremer.tutti.ui.swing.util.TuttiErrorHelper; @@ -548,22 +549,26 @@ return serviceContext.getService(TuttiReferentialSynchronizeService.class); } - public TuttiProtocolImportExportService getTuttiProtocolImportExportService() { - return serviceContext.getService(TuttiProtocolImportExportService.class); + public ProtocolImportExportService getTuttiProtocolImportExportService() { + return serviceContext.getService(ProtocolImportExportService.class); } - public TuttiPupitriImportExportService getTuttiPupitriImportExportService() { - return serviceContext.getService(TuttiPupitriImportExportService.class); + public PupitriImportExportService getTuttiPupitriImportExportService() { + return serviceContext.getService(PupitriImportExportService.class); } - public TuttiReferentialImportExportService getTuttiReferentialImportExportService() { - return serviceContext.getService(TuttiReferentialImportExportService.class); + public ReferentialImportExportService getTuttiReferentialImportExportService() { + return serviceContext.getService(ReferentialImportExportService.class); } - public TuttiWeightComputingService getTuttiWeightComputingService() { - return serviceContext.getService(TuttiWeightComputingService.class); + public WeightComputingService getWeightComputingService() { + return serviceContext.getService(WeightComputingService.class); } + public WeightCleaningService getWeightCleaningService() { + return serviceContext.getService(WeightCleaningService.class); + } + public ValidateCruiseOperationsService getValidateCruiseOperationsService() { return serviceContext.getService(ValidateCruiseOperationsService.class); } @@ -580,16 +585,16 @@ return serviceContext.getService(TuttiExportService.class); } - public TuttiCatchesSumatraExportService getCatchesSumatraExportService() { - return serviceContext.getService(TuttiCatchesSumatraExportService.class); + public CatchesSumatraExportService getCatchesSumatraExportService() { + return serviceContext.getService(CatchesSumatraExportService.class); } - public TuttiMultiPostImportService getMultiPostImportService() { - return serviceContext.getService(TuttiMultiPostImportService.class); + public MultiPostImportService getMultiPostImportService() { + return serviceContext.getService(MultiPostImportService.class); } - public TuttiMultiPostExportService getMultiPostExportService() { - return serviceContext.getService(TuttiMultiPostExportService.class); + public MultiPostExportService getMultiPostExportService() { + return serviceContext.getService(MultiPostExportService.class); } public boolean useRealPersistenceService() { Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/config/TuttiApplicationConfig.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/config/TuttiApplicationConfig.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/config/TuttiApplicationConfig.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,9 +26,9 @@ import com.google.common.base.Charsets; import fr.ifremer.tutti.TuttiTechnicalException; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.service.config.TuttiServiceConfig; import fr.ifremer.tutti.service.config.TuttiServiceConfigOption; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; import fr.ifremer.tutti.ui.swing.util.editor.CoordinateEditorType; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; @@ -260,23 +260,23 @@ } public WeightUnit getSpeciesWeightUnit() { - return applicationConfig.getOption(WeightUnit.class, TuttiApplicationConfigOption.WEIGHT_UNIT_SPECIES.getKey()); + return serviceConfig.getSpeciesWeightUnit(); } public WeightUnit getBenthosWeightUnit() { - return applicationConfig.getOption(WeightUnit.class, TuttiApplicationConfigOption.WEIGHT_UNIT_BENTHOS.getKey()); + return serviceConfig.getBenthosWeightUnit(); } public WeightUnit getMarineLitterWeightUnit() { - return applicationConfig.getOption(WeightUnit.class, TuttiApplicationConfigOption.WEIGHT_UNIT_MARINE_LITTER.getKey()); + return serviceConfig.getMarineLitterWeightUnit(); } public WeightUnit getIndividualObservationWeightUnit() { - return applicationConfig.getOption(WeightUnit.class, TuttiApplicationConfigOption.WEIGHT_UNIT_INDIVIDUAL_OBSERVATION.getKey()); + return serviceConfig.getIndividualObservationWeightUnit(); } public WeightUnit getAccidentalCatchWeightUnit() { - return applicationConfig.getOption(WeightUnit.class, TuttiApplicationConfigOption.WEIGHT_UNIT_ACCIDENTAL_CATCH.getKey()); + return serviceConfig.getAccidentalCatchWeightUnit(); } public KeyStroke getShortCut(String actionName) { Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/config/TuttiApplicationConfigOption.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/config/TuttiApplicationConfigOption.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/config/TuttiApplicationConfigOption.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -24,7 +24,6 @@ * #L% */ -import fr.ifremer.tutti.ui.swing.util.WeightUnit; import fr.ifremer.tutti.ui.swing.util.editor.CoordinateEditorType; import org.nuiton.config.ConfigOptionDef; @@ -223,41 +222,6 @@ // "ifremer" by default "ef399a6e6ec62c6e142440241a5b98f8", String.class - ), - - WEIGHT_UNIT_SPECIES( - "tutti.ui.weight.unit.species", - n_("tutti.config.option.ui.weight.unit.species.description"), - WeightUnit.KG.name(), - WeightUnit.class - ), - - WEIGHT_UNIT_BENTHOS( - "tutti.ui.weight.unit.benthos", - n_("tutti.config.option.ui.weight.unit.benthos.description"), - WeightUnit.G.name(), - WeightUnit.class - ), - - WEIGHT_UNIT_MARINE_LITTER( - "tutti.ui.weight.unit.marineLitter", - n_("tutti.config.option.ui.weight.unit.marineLitter.description"), - WeightUnit.KG.name(), - WeightUnit.class - ), - - WEIGHT_UNIT_INDIVIDUAL_OBSERVATION( - "tutti.ui.weight.unit.individualObservation", - n_("tutti.config.option.ui.weight.unit.individualObservation.description"), - WeightUnit.G.name(), - WeightUnit.class - ), - - WEIGHT_UNIT_ACCIDENTAL_CATCH( - "tutti.ui.weight.unit.accidentalCatch", - n_("tutti.config.option.ui.weight.unit.accidentalCatch.description"), - WeightUnit.KG.name(), - WeightUnit.class ); /** Configuration key. */ Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/config/TuttiConfigUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/config/TuttiConfigUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/config/TuttiConfigUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -163,11 +163,11 @@ helper.addCategory(n_("tutti.config.category.weightUnit"), n_("tutti.config.category.weightUnit.description"), CALLBACK_UI) - .addOption(TuttiApplicationConfigOption.WEIGHT_UNIT_SPECIES) - .addOption(TuttiApplicationConfigOption.WEIGHT_UNIT_BENTHOS) - .addOption(TuttiApplicationConfigOption.WEIGHT_UNIT_MARINE_LITTER) - .addOption(TuttiApplicationConfigOption.WEIGHT_UNIT_INDIVIDUAL_OBSERVATION) - .addOption(TuttiApplicationConfigOption.WEIGHT_UNIT_ACCIDENTAL_CATCH); + .addOption(TuttiServiceConfigOption.WEIGHT_UNIT_SPECIES) + .addOption(TuttiServiceConfigOption.WEIGHT_UNIT_BENTHOS) + .addOption(TuttiServiceConfigOption.WEIGHT_UNIT_MARINE_LITTER) + .addOption(TuttiServiceConfigOption.WEIGHT_UNIT_INDIVIDUAL_OBSERVATION) + .addOption(TuttiServiceConfigOption.WEIGHT_UNIT_ACCIDENTAL_CATCH); // Technical category Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportCruiseAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportCruiseAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportCruiseAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -28,7 +28,6 @@ import fr.ifremer.tutti.TuttiBusinessException; import fr.ifremer.tutti.persistence.ProgressionModel; import fr.ifremer.tutti.persistence.entities.data.Cruise; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.service.export.TuttiExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -99,19 +98,19 @@ // (check cruise / export cruise / gear caracteristics / operation / parameter / accidental catches / catches / individual observation / species) / zip progressionModel.setTotal(10); - TuttiProtocol protocol = null; - if (getContext().isProtocolFilled()) { - protocol = getDataContext().getProtocol(); - if (log.isInfoEnabled()) { - log.info("Will use protocol " + protocol.getName()); - } - } +// TuttiProtocol protocol = null; +// if (getContext().isProtocolFilled()) { +// protocol = getDataContext().getProtocol(); +// if (log.isInfoEnabled()) { +// log.info("Will use protocol " + protocol.getName()); +// } +// } TuttiBusinessException exportError = null; TuttiExportService service = getContext().getTuttiExportService(); try { - service.exportCruise(cruise.getId(), protocol, file, progressionModel); + service.exportCruise(cruise.getId(), file, progressionModel); } catch (TuttiBusinessException e) { String errorMessage; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportCruiseForSumatraAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportCruiseForSumatraAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportCruiseForSumatraAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,7 @@ import com.google.common.base.Preconditions; import fr.ifremer.tutti.persistence.entities.data.Cruise; -import fr.ifremer.tutti.service.sumatra.TuttiCatchesSumatraExportService; +import fr.ifremer.tutti.service.sumatra.CatchesSumatraExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -94,7 +94,7 @@ } // export catches - TuttiCatchesSumatraExportService service = + CatchesSumatraExportService service = getContext().getCatchesSumatraExportService(); service.exportCruiseForSumatra(file, cruise.getId()); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportProgramAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportProgramAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportProgramAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -29,7 +29,6 @@ import fr.ifremer.tutti.persistence.ProgressionModel; import fr.ifremer.tutti.persistence.entities.data.Cruise; import fr.ifremer.tutti.persistence.entities.data.Program; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.service.export.TuttiExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -102,18 +101,18 @@ setProgressionModel(progressionModel); progressionModel.setTotal(9 * allCruise.size() + 1); - TuttiProtocol protocol = null; - if (getContext().isProtocolFilled()) { - protocol = getDataContext().getProtocol(); - if (log.isInfoEnabled()) { - log.info("Will use protocol " + protocol.getName()); - } - } +// TuttiProtocol protocol = null; +// if (getContext().isProtocolFilled()) { +// protocol = getDataContext().getProtocol(); +// if (log.isInfoEnabled()) { +// log.info("Will use protocol " + protocol.getName()); +// } +// } TuttiBusinessException exportError = null; TuttiExportService service = getContext().getTuttiExportService(); try { - service.exportProgram(program.getId(), protocol, file, progressionModel); + service.exportProgram(program.getId(), file, progressionModel); } catch (TuttiBusinessException e) { String errorMessage; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportProtocolAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportProtocolAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ExportProtocolAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,7 @@ import com.google.common.base.Preconditions; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -92,7 +92,7 @@ } // export protocol - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); service.exportProtocol(protocol, file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ImportProtocolAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ImportProtocolAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/ImportProtocolAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -30,7 +30,7 @@ import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocols; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.TuttiScreen; import fr.ifremer.tutti.ui.swing.content.AbstractChangeScreenAction; import fr.ifremer.tutti.ui.swing.content.MainUIHandler; @@ -93,7 +93,7 @@ log.info("Will import protocol file: " + file); } - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); protocol = service.importProtocol(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/SelectCruiseUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/SelectCruiseUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/home/SelectCruiseUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -134,11 +134,11 @@ } } else { - TuttiProtocol selectedProtocol = null; - if (context.isProgramFilled()) { - selectedProtocol = getDataContext().getProtocol(); - } - model.setProtocol(selectedProtocol); +// TuttiProtocol selectedProtocol = null; +// if (context.isProgramFilled()) { +// selectedProtocol = getDataContext().getProtocol(); +// } + model.setProtocol(getDataContext().getProtocol()); } ui.setContextValue(model); } Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -36,7 +36,7 @@ import fr.ifremer.tutti.persistence.entities.referential.TuttiLocation; import fr.ifremer.tutti.service.PersistenceService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; -import fr.ifremer.tutti.ui.swing.content.operation.catches.ComputeWeightsAction; +import fr.ifremer.tutti.ui.swing.content.operation.catches.ComputeBatchWeightsAction; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUI; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUIModel; import fr.ifremer.tutti.ui.swing.content.operation.catches.SaveCatchBatchAction; @@ -104,7 +104,7 @@ * * @since 1.1 */ - protected ComputeWeightsAction computeWeightsAction; + protected ComputeBatchWeightsAction computeBatchWeightsAction; /** * Delegate action to save catch batch. @@ -200,11 +200,11 @@ return saveCatchBatchAction; } - protected ComputeWeightsAction getComputeWeightsAction() { - if (computeWeightsAction == null) { - computeWeightsAction = new ComputeWeightsAction(getUI().getCatchesTabContent().getHandler()); + protected ComputeBatchWeightsAction getComputeBatchWeightsAction() { + if (computeBatchWeightsAction == null) { + computeBatchWeightsAction = new ComputeBatchWeightsAction(getUI().getCatchesTabContent().getHandler()); } - return computeWeightsAction; + return computeBatchWeightsAction; } @Override Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/AbstractExportMultiPostAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/AbstractExportMultiPostAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/AbstractExportMultiPostAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,7 @@ import fr.ifremer.tutti.persistence.entities.data.FishingOperation; import fr.ifremer.tutti.service.DecoratorService; -import fr.ifremer.tutti.service.catches.multipost.TuttiMultiPostExportService; +import fr.ifremer.tutti.service.catches.multipost.MultiPostExportService; import fr.ifremer.tutti.ui.swing.util.AbstractTuttiUIHandler; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; @@ -45,7 +45,7 @@ protected FishingOperation currentOperation; - protected TuttiMultiPostExportService multiPostImportExportService; + protected MultiPostExportService multiPostImportExportService; public AbstractExportMultiPostAction(H handler) { super(handler, false); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/AbstractImportMultiPostAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/AbstractImportMultiPostAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/AbstractImportMultiPostAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.service.catches.multipost.TuttiMultiPostImportService; +import fr.ifremer.tutti.service.catches.multipost.MultiPostImportService; import fr.ifremer.tutti.ui.swing.content.operation.EditFishingOperationAction; import fr.ifremer.tutti.ui.swing.content.operation.FishingOperationsUI; import fr.ifremer.tutti.ui.swing.util.AbstractTuttiUIHandler; @@ -47,7 +47,7 @@ protected EditFishingOperationAction editAction; - protected TuttiMultiPostImportService multiPostImportExportService; + protected MultiPostImportService multiPostImportExportService; public AbstractImportMultiPostAction(H handler) { super(handler, false); Added: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/CleanBatchWeightsAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/CleanBatchWeightsAction.java (rev 0) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/CleanBatchWeightsAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,119 @@ +package fr.ifremer.tutti.ui.swing.content.operation.catches; + +import com.google.common.collect.Multimap; +import fr.ifremer.tutti.persistence.InvalidBatchModelException; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.service.catches.WeightCleaningService; +import fr.ifremer.tutti.ui.swing.util.AbstractTuttiUIHandler; +import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JOptionPane; + +import static org.nuiton.i18n.I18n._; + +/** + * To remove weight in double for species and benthos rows. + * <p/> + * Created on 9/27/13. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 2.6 + */ +public class CleanBatchWeightsAction extends AbstractTuttiAction<EditCatchesUIModel, EditCatchesUI, EditCatchesUIHandler> { + + /** Logger. */ + private static final Log log = + LogFactory.getLog(CleanBatchWeightsAction.class); + + protected final WeightCleaningService cleaningService; + + protected int nbErrors; + + public CleanBatchWeightsAction(EditCatchesUIHandler handler) { + super(handler, false); + cleaningService = getContext().getWeightCleaningService(); + } + + @Override + public boolean prepareAction() throws Exception { + boolean doAction = super.prepareAction(); + if (doAction) { + + + // do a check + FishingOperation fishingOperation = getModel().getFishingOperation(); + Multimap<String, String> errors = cleaningService.checkFishingOperation(fishingOperation.getId()); + + nbErrors = errors.size(); + + if (nbErrors == 0) { + + // no errors + + sendMessage(_("tutti.editCatchBatch.action.cleanWeights.no.double.weight.detected")); + doAction = false; + } else { + + // show errors to user and ask him to apply change + + String errorsStr = cleaningService.errorsToString(errors); + String htmlMessage = String.format( + AbstractTuttiUIHandler.CONFIRMATION_FORMAT, + _("tutti.editCatchBatch.action.cleanWeights.double.weight.detected", errorsStr), + _("tutti.editCatchBatch.action.cleanWeights.help")); + + int answer = JOptionPane.showConfirmDialog( + getContext().getActionUI(), + htmlMessage, + _("tutti.editCatchBatch.action.cleanWieghts.resume.title"), + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); + + doAction = (answer == JOptionPane.OK_OPTION); + + } + } + return doAction; + } + + @Override + public void doAction() throws Exception { + + EditCatchesUIModel model = getModel(); + FishingOperation fishingOperation = getModel().getFishingOperation(); + model.setLoadingData(true); + + cleaningService.cleanFishingOperation(fishingOperation.getId()); + + try { + + getUI().getSpeciesTabContent().getHandler().selectFishingOperation(fishingOperation); + } catch (InvalidBatchModelException e) { + + // invalid sample category model for species batches + if (log.isDebugEnabled()) { + log.debug("Invalid sample category model for species batches", e); + } + } + + try { + getUI().getBenthosTabContent().getHandler().selectFishingOperation(fishingOperation); + } catch (InvalidBatchModelException e) { + + // invalid sample category model for benthos batches + if (log.isDebugEnabled()) { + log.debug("Invalid sample category model for benthos batches", e); + } + } + } + + @Override + public void postSuccessAction() { + super.postSuccessAction(); + + sendMessage(_("tutti.editCatchBatch.action.cleanWeights.done", nbErrors)); + } + +} \ No newline at end of file Property changes on: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/CleanBatchWeightsAction.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Copied: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeBatchWeightsAction.java (from rev 1246, trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java) =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeBatchWeightsAction.java (rev 0) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeBatchWeightsAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -0,0 +1,324 @@ + +package fr.ifremer.tutti.ui.swing.content.operation.catches; + +/* + * #%L + * Tutti :: UI + * $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.Multimap; +import fr.ifremer.tutti.persistence.entities.TuttiEntities; +import fr.ifremer.tutti.persistence.entities.data.BatchContainer; +import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; +import fr.ifremer.tutti.persistence.entities.data.CatchBatch; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; +import fr.ifremer.tutti.persistence.entities.data.SampleCategory; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.service.PersistenceService; +import fr.ifremer.tutti.service.catches.TuttiWeightComputingException; +import fr.ifremer.tutti.service.catches.WeightCleaningService; +import fr.ifremer.tutti.service.catches.WeightComputingService; +import fr.ifremer.tutti.ui.swing.content.operation.catches.benthos.BenthosBatchRowModel; +import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SpeciesBatchRowModel; +import fr.ifremer.tutti.ui.swing.util.AbstractTuttiUIHandler; +import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; +import fr.ifremer.tutti.ui.swing.util.table.AbstractSelectTableAction; + +import javax.swing.JOptionPane; +import java.util.List; + +import static org.nuiton.i18n.I18n._; + +/** + * @author kmorin <kmorin@codelutin.com> + * @since 1.0 + */ +public class ComputeBatchWeightsAction extends AbstractTuttiAction<EditCatchesUIModel, EditCatchesUI, EditCatchesUIHandler> { + + protected final WeightCleaningService cleaningService; + + public ComputeBatchWeightsAction(EditCatchesUIHandler handler) { + super(handler, false); + cleaningService = getContext().getWeightCleaningService(); + } + + @Override + public boolean prepareAction() throws Exception { + boolean doAction = super.prepareAction(); + if (doAction) { + + // do a check of double weights + FishingOperation fishingOperation = getModel().getFishingOperation(); + Multimap<String, String> errors = cleaningService.checkFishingOperation(fishingOperation.getId()); + + if (errors.isEmpty()) { + + // no errors + + sendMessage(_("tutti.editCatchBatch.action.computeWeights.no.double.weight.detected")); + } else { + + // show errors to user as warning + + String errorsStr = cleaningService.errorsToString(errors); + String htmlMessage = _("tutti.editCatchBatch.action.computeWeights.double.weight.detected", errorsStr); + + JOptionPane.showMessageDialog(getContext().getActionUI(), + htmlMessage, + _("tutti.editCatchBatch.action.computeWeights.double.weight.detected.title"), + JOptionPane.WARNING_MESSAGE); + + + } + } + return doAction; + } + + @Override + public void doAction() throws Exception { + PersistenceService persistenceService = getContext().getPersistenceService(); + + WeightComputingService weightComputingService = getContext().getWeightComputingService(); + + EditCatchesUIModel model = getModel(); + model.setLoadingData(true); + + // --------- + // Compute species batches + // --------- + + BatchContainer<SpeciesBatch> computedSpeciesBatches; + Float totalSpeciesSortedWeight; + try { + computedSpeciesBatches = + weightComputingService.getComputedSpeciesBatches(model.getFishingOperation()); + totalSpeciesSortedWeight = computeSpeciesBatches(persistenceService, computedSpeciesBatches); + + } catch (TuttiWeightComputingException e) { + getUI().getTabPane().setSelectedIndex(1); + + int index = e.getIndex(); + SpeciesBatchRowModel row = getUI().getSpeciesTabContent().getModel().getRows().get(index); + int column; + if (SpeciesBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT.equals(e.getProperty())) { + column = getFinestCategoryColumn(row.getFinestCategory().getCategoryId()); + } else { + column = 6; + } + AbstractSelectTableAction.doSelectCell(getUI().getSpeciesTabContent().getTable(), index, column); + + throw e; + } + + // --------- + // Compute benthos batches + // --------- + + BatchContainer<BenthosBatch> computedBenthosBatches; + Float totalBenthosSortedWeight; + try { + computedBenthosBatches = + weightComputingService.getComputedBenthosBatches(model.getFishingOperation()); + totalBenthosSortedWeight = computeBenthosBatches(persistenceService, computedBenthosBatches); + + } catch (TuttiWeightComputingException e) { + getUI().getTabPane().setSelectedIndex(2); + + int index = e.getIndex(); + BenthosBatchRowModel row = getUI().getBenthosTabContent().getModel().getRows().get(index); + int column; + if (BenthosBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT.equals(e.getProperty())) { + column = getFinestCategoryColumn(row.getFinestCategory().getCategoryId()); + } else { + column = 6; + } + AbstractSelectTableAction.doSelectCell(getUI().getBenthosTabContent().getTable(), index, column); + + throw e; + } + + // --------- + // Compute marine litter batches + // --------- + + BatchContainer<MarineLitterBatch> computedMarineLitterBatches; + try { + computedMarineLitterBatches = + weightComputingService.getComputedMarineLitterBatches(model.getFishingOperation(), + model.getMarineLitterTotalWeight()); + + } catch (TuttiWeightComputingException e) { + getUI().getTabPane().setSelectedIndex(3); + AbstractSelectTableAction.doSelectCell(getUI().getMarineLitterTabContent().getTable(), e.getIndex(), 3); + throw e; + } + + // --------- + // Check species rates + // --------- + + Float rate = getConfig().getDifferenceRateBetweenSortedAndTotalWeights(); + if (model.getSpeciesTotalSortedWeight() != null + && model.getSpeciesTotalSortedWeight() >= totalSpeciesSortedWeight + && model.getSpeciesTotalSortedWeight() < (1 + rate / 100) * totalSpeciesSortedWeight) { + + // Si le "Poids total VRAC" est saisi est que sa valeur + // est supérieure de moins de x% (x en configuration) + // du "Poids total Vrac trié", demander confirmation que + // le "Poids total VRAC" est bien une valeur observée + // sinon la remplacer par le "Poids total Vrac trié" + + getUI().getTabPane().setSelectedIndex(1); + + String htmlMessage = String.format( + AbstractTuttiUIHandler.CONFIRMATION_FORMAT, + _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.message.species", rate), + _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.help")); + + int answer = JOptionPane.showConfirmDialog(getContext().getActionUI(), + htmlMessage, + _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.title"), + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE); + + if (answer == JOptionPane.NO_OPTION) { + model.setSpeciesTotalSortedWeight(null); + model.setSpeciesTotalSortedComputedWeight(totalSpeciesSortedWeight); + } + } + + // --------- + // Check benthos rates + // --------- + + if (model.getBenthosTotalSortedWeight() != null + && model.getBenthosTotalSortedWeight() >= totalBenthosSortedWeight + && model.getBenthosTotalSortedWeight() < (1 + rate / 100) * totalBenthosSortedWeight) { + + // Si le "Poids total VRAC" est saisi est que sa valeur + // est supérieure de moins de x% (x en configuration) + // du "Poids total Vrac trié", demander confirmation que + // le "Poids total VRAC" est bien une valeur observée + // sinon la remplacer par le "Poids total Vrac trié" + + getUI().getTabPane().setSelectedIndex(2); + + String htmlMessage = String.format( + AbstractTuttiUIHandler.CONFIRMATION_FORMAT, + _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.message.benthos", rate), + _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.help")); + + int answer = JOptionPane.showConfirmDialog(getContext().getActionUI(), + htmlMessage, + _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.title"), + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE); + + if (answer == JOptionPane.NO_OPTION) { + model.setBenthosTotalSortedWeight(null); + model.setBenthosTotalSortedComputedWeight(totalBenthosSortedWeight); + } + } + + boolean modified = model.isModify(); + CatchBatch catchBatch = model.toEntity(); + weightComputingService.computeCatchBatchWeights(catchBatch, + computedSpeciesBatches, + computedBenthosBatches, + computedMarineLitterBatches); + model.fromEntity(catchBatch); + model.setLoadingData(false); + + model.setModify(modified); + } + + @Override + public void postSuccessAction() { + super.postSuccessAction(); + + getUI().repaint(); + } + + //------------------------------------------------------------------------// + //-- Internal methods --// + //------------------------------------------------------------------------// + + protected Float computeSpeciesBatches(PersistenceService persistenceService, BatchContainer<SpeciesBatch> computedSpeciesBatches) { + Float totalSortedWeight = 0f; + + if (computedSpeciesBatches != null) { + List<SpeciesBatchRowModel> rows = Lists.newArrayList(); + List<SpeciesBatch> children = computedSpeciesBatches.getChildren(); + for (SpeciesBatch batch : children) { + SpeciesBatchRowModel row = getUI().getSpeciesTabContent().getHandler().loadBatch(batch, null, rows); + if (persistenceService.isVracSpeciesBatch(row)) { + SampleCategory<?> sampleCategory = row.getFirstSampleCategory(); + Float weight = TuttiEntities.getValueOrComputedValue( + sampleCategory.getCategoryWeight(), + sampleCategory.getComputedWeight()); + totalSortedWeight += weight; + } + } + getUI().getSpeciesTabContent().getModel().setRows(rows); + } + + return totalSortedWeight; + } + + protected Float computeBenthosBatches(PersistenceService persistenceService, BatchContainer<BenthosBatch> computedBenthosBatches) { + Float totalSortedWeight = 0f; + + if (computedBenthosBatches != null) { + List<BenthosBatchRowModel> rows = Lists.newArrayList(); + List<BenthosBatch> children = computedBenthosBatches.getChildren(); + for (BenthosBatch batch : children) { + BenthosBatchRowModel row = getUI().getBenthosTabContent().getHandler().loadBatch(batch, null, rows); + + if (persistenceService.isVracBenthosBatch(row)) { + SampleCategory<?> sampleCategory = row.getFirstSampleCategory(); + Float weight = TuttiEntities.getValueOrComputedValue( + sampleCategory.getCategoryWeight(), + sampleCategory.getComputedWeight()); + totalSortedWeight += weight; + } + } + getUI().getBenthosTabContent().getModel().setRows(rows); + + } + return totalSortedWeight; + } + + protected int getFinestCategoryColumn(Integer categoryId) { + int column = 1; + + List<Integer> samplingOrderIds = getConfig().getServiceConfig().getSamplingOrderIds(); + + int index = samplingOrderIds.indexOf(categoryId); + if (index > -1) { + column += index + 1; + } + + return column; + } +} Deleted: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,304 +0,0 @@ - -package fr.ifremer.tutti.ui.swing.content.operation.catches; - -/* - * #%L - * Tutti :: UI - * $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 fr.ifremer.tutti.persistence.entities.TuttiEntities; -import fr.ifremer.tutti.persistence.entities.data.BatchContainer; -import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; -import fr.ifremer.tutti.persistence.entities.data.CatchBatch; -import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; -import fr.ifremer.tutti.persistence.entities.data.SampleCategory; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.catches.TuttiWeightComputingException; -import fr.ifremer.tutti.service.catches.TuttiWeightComputingService; -import fr.ifremer.tutti.ui.swing.content.operation.catches.benthos.BenthosBatchRowModel; -import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SpeciesBatchRowModel; -import fr.ifremer.tutti.ui.swing.util.AbstractTuttiUIHandler; -import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; -import fr.ifremer.tutti.ui.swing.util.table.AbstractSelectTableAction; - -import javax.swing.JOptionPane; -import java.util.List; - -import static org.nuiton.i18n.I18n._; - -/** - * @author kmorin <kmorin@codelutin.com> - * @since 1.0 - */ -public class ComputeWeightsAction extends AbstractTuttiAction<EditCatchesUIModel, EditCatchesUI, EditCatchesUIHandler> { - - public ComputeWeightsAction(EditCatchesUIHandler handler) { - super(handler, false); - } - - //FIXME Do weightUnit conversion... - @Override - public void doAction() throws Exception { - PersistenceService persistenceService = getContext().getPersistenceService(); - - TuttiWeightComputingService tuttiWeightComputingService = getContext().getTuttiWeightComputingService(); - - EditCatchesUIModel model = getModel(); - model.setLoadingData(true); - - // --------- - // Compute species batches - // --------- - - BatchContainer<SpeciesBatch> computedSpeciesBatches; - Float totalSpeciesSortedWeight; - try { - computedSpeciesBatches = - tuttiWeightComputingService.getComputedSpeciesBatches(model.getFishingOperation()); - totalSpeciesSortedWeight = computeSpeciesBatches(persistenceService, computedSpeciesBatches); - - } catch (TuttiWeightComputingException e) { - getUI().getTabPane().setSelectedIndex(1); - - int index = e.getIndex(); - SpeciesBatchRowModel row = getUI().getSpeciesTabContent().getModel().getRows().get(index); - int column; - if (SpeciesBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT.equals(e.getProperty())) { - column = getFinestCategoryColumn(row.getFinestCategory().getCategoryId()); - } else { - column = 6; - } - AbstractSelectTableAction.doSelectCell(getUI().getSpeciesTabContent().getTable(), index, column); - - throw e; - } - - // --------- - // Compute benthos batches - // --------- - - BatchContainer<BenthosBatch> computedBenthosBatches; - Float totalBenthosSortedWeight; - try { - computedBenthosBatches = - tuttiWeightComputingService.getComputedBenthosBatches(model.getFishingOperation()); - totalBenthosSortedWeight = computeBenthosBatches(persistenceService, computedBenthosBatches); - - } catch (TuttiWeightComputingException e) { - getUI().getTabPane().setSelectedIndex(2); - - int index = e.getIndex(); - BenthosBatchRowModel row = getUI().getBenthosTabContent().getModel().getRows().get(index); - int column; - if (BenthosBatch.PROPERTY_SAMPLE_CATEGORY_WEIGHT.equals(e.getProperty())) { - column = getFinestCategoryColumn(row.getFinestCategory().getCategoryId()); - } else { - column = 6; - } - AbstractSelectTableAction.doSelectCell(getUI().getBenthosTabContent().getTable(), index, column); - - throw e; - } - - // --------- - // Compute marine litter batches - // --------- - - BatchContainer<MarineLitterBatch> computedMarineLitterBatches; - try { - computedMarineLitterBatches = - tuttiWeightComputingService.getComputedMarineLitterBatches(model.getFishingOperation(), - model.getMarineLitterTotalWeight()); - - } catch (TuttiWeightComputingException e) { - getUI().getTabPane().setSelectedIndex(3); - AbstractSelectTableAction.doSelectCell(getUI().getMarineLitterTabContent().getTable(), e.getIndex(), 3); - throw e; - } - - // --------- - // Check species rates - // --------- - - Float rate = getConfig().getDifferenceRateBetweenSortedAndTotalWeights(); - if (model.getSpeciesTotalSortedWeight() != null - && model.getSpeciesTotalSortedWeight() >= totalSpeciesSortedWeight - && model.getSpeciesTotalSortedWeight() < (1 + rate / 100) * totalSpeciesSortedWeight) { - - // Si le "Poids total VRAC" est saisi est que sa valeur - // est supérieure de moins de x% (x en configuration) - // du "Poids total Vrac trié", demander confirmation que - // le "Poids total VRAC" est bien une valeur observée - // sinon la remplacer par le "Poids total Vrac trié" - - getUI().getTabPane().setSelectedIndex(1); - - String htmlMessage = String.format( - AbstractTuttiUIHandler.CONFIRMATION_FORMAT, - _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.message.species", rate), - _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.help")); - - int answer = JOptionPane.showConfirmDialog(getContext().getActionUI(), - htmlMessage, - _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.title"), - JOptionPane.YES_NO_OPTION, - JOptionPane.QUESTION_MESSAGE); - - if (answer == JOptionPane.NO_OPTION) { - model.setSpeciesTotalSortedWeight(null); - model.setSpeciesTotalSortedComputedWeight(totalSpeciesSortedWeight); - } - } - - // --------- - // Check benthos rates - // --------- - - if (model.getBenthosTotalSortedWeight() != null - && model.getBenthosTotalSortedWeight() >= totalBenthosSortedWeight - && model.getBenthosTotalSortedWeight() < (1 + rate / 100) * totalBenthosSortedWeight) { - - // Si le "Poids total VRAC" est saisi est que sa valeur - // est supérieure de moins de x% (x en configuration) - // du "Poids total Vrac trié", demander confirmation que - // le "Poids total VRAC" est bien une valeur observée - // sinon la remplacer par le "Poids total Vrac trié" - - getUI().getTabPane().setSelectedIndex(2); - - String htmlMessage = String.format( - AbstractTuttiUIHandler.CONFIRMATION_FORMAT, - _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.message.benthos", rate), - _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.help")); - - int answer = JOptionPane.showConfirmDialog(getContext().getActionUI(), - htmlMessage, - _("tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.title"), - JOptionPane.YES_NO_OPTION, - JOptionPane.QUESTION_MESSAGE); - - if (answer == JOptionPane.NO_OPTION) { - model.setBenthosTotalSortedWeight(null); - model.setBenthosTotalSortedComputedWeight(totalBenthosSortedWeight); - } - } - - boolean modified = model.isModify(); - CatchBatch catchBatch = model.toEntity(); - tuttiWeightComputingService.computeCatchBatchWeights(catchBatch, - computedSpeciesBatches, - computedBenthosBatches, - computedMarineLitterBatches); -// model.setCatchBatch(catchBatch); - model.fromEntity(catchBatch); - model.setLoadingData(false); - - model.setModify(modified); - } - - @Override - public void postSuccessAction() { - super.postSuccessAction(); - - getUI().repaint(); - } - - //------------------------------------------------------------------------// - //-- Internal methods --// - //------------------------------------------------------------------------// - - protected Float computeSpeciesBatches(PersistenceService persistenceService, BatchContainer<SpeciesBatch> computedSpeciesBatches) { - Float totalSortedWeight = 0f; - - if (computedSpeciesBatches != null) { - List<SpeciesBatchRowModel> rows = Lists.newArrayList(); - List<SpeciesBatch> children = computedSpeciesBatches.getChildren(); - for (SpeciesBatch batch : children) { - SpeciesBatchRowModel row = getUI().getSpeciesTabContent().getHandler().loadBatch(batch, null, rows); -// Float weight = row.getSortedUnsortedCategoryWeight(); -// if (weight == null) { -// weight = row.getSortedUnsortedCategoryComputedWeight(); -// } - if (persistenceService.isVracSpeciesBatch(row)) { - SampleCategory<?> sampleCategory = row.getFirstSampleCategory(); - Float weight = TuttiEntities.getValueOrComputedValue( - sampleCategory.getCategoryWeight(), - sampleCategory.getComputedWeight()); - totalSortedWeight += weight; - } -// if (SortedUnsortedEnum.SORTED.matchValue( -// row.getSortedUnsortedCategoryValue())) { -// totalSortedWeight += weight; -// } - } - getUI().getSpeciesTabContent().getModel().setRows(rows); - } - - return totalSortedWeight; - } - - protected Float computeBenthosBatches(PersistenceService persistenceService, BatchContainer<BenthosBatch> computedBenthosBatches) { - Float totalSortedWeight = 0f; - - if (computedBenthosBatches != null) { - List<BenthosBatchRowModel> rows = Lists.newArrayList(); - List<BenthosBatch> children = computedBenthosBatches.getChildren(); - for (BenthosBatch batch : children) { - BenthosBatchRowModel row = getUI().getBenthosTabContent().getHandler().loadBatch(batch, null, rows); -// Float weight = row.getSortedUnsortedCategoryWeight(); -// if (weight == null) { -// weight = row.getSortedUnsortedCategoryComputedWeight(); -// -// } - - if (persistenceService.isVracBenthosBatch(row)) { - SampleCategory<?> sampleCategory = row.getFirstSampleCategory(); - Float weight = TuttiEntities.getValueOrComputedValue( - sampleCategory.getCategoryWeight(), - sampleCategory.getComputedWeight()); - totalSortedWeight += weight; - } -// if (SortedUnsortedEnum.SORTED.matchValue(row.getSortedUnsortedCategoryValue())) { -// totalSortedWeight += weight; -// } - } - getUI().getBenthosTabContent().getModel().setRows(rows); - - } - return totalSortedWeight; - } - - protected int getFinestCategoryColumn(Integer categoryId) { - int column = 1; - - List<Integer> samplingOrderIds = getConfig().getServiceConfig().getSamplingOrderIds(); - - int index = samplingOrderIds.indexOf(categoryId); - if (index > -1) { - column += index + 1; - } - - return column; - } -} Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.css =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.css 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.css 2013-09-28 12:15:25 UTC (rev 1247) @@ -28,8 +28,6 @@ bean: {model}; showReset: true; useFloat: true; - /*numberPattern: {DECIMAL3_PATTERN};*/ - _selectOnFocus: {true}; } TuttiComputedOrNotDataEditor { @@ -37,8 +35,6 @@ showPopupButton: {handler.getConfig().isShowNumberEditorButton()}; showReset: true; useFloat: true; - /*numberPattern: {DECIMAL3_PATTERN}; - decimalNumber: 3;*/ computedDataColor: {handler.getConfig().getColorComputedWeights()}; } @@ -350,11 +346,20 @@ _help: {"tutti.editCatchBatch.action.cancelEditCatchBatch.help"}; } +#cleanSpeciesBatchButton { + actionIcon: clean; + text: "tutti.editCatchBatch.action.cleanWeights"; + toolTipText: "tutti.editCatchBatch.action.cleanWeights.tip"; + i18nMnemonic: "tutti.editCatchBatch.action.cleanWeights.mnemonic"; + _tuttiAction: {CleanBatchWeightsAction.class}; + _help: {"tutti.editCatchBatch.action.cleanWeights.help"}; +} + #computeSpeciesBatchButton { actionIcon: generate; text: "tutti.editCatchBatch.action.computeWeights"; toolTipText: "tutti.editCatchBatch.action.computeWeights.tip"; i18nMnemonic: "tutti.editCatchBatch.action.computeWeights.mnemonic"; - _tuttiAction: {ComputeWeightsAction.class}; + _tuttiAction: {ComputeBatchWeightsAction.class}; _help: {"tutti.editCatchBatch.action.computeWeights.help"}; } Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.jaxx =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.jaxx 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUI.jaxx 2013-09-28 12:15:25 UTC (rev 1247) @@ -436,6 +436,9 @@ <JButton id='saveButton'/> </cell> <cell weightx="1"> + <JButton id='cleanSpeciesBatchButton'/> + </cell> + <cell weightx="1"> <JButton id='computeSpeciesBatchButton'/> </cell> </row> Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUIModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUIModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/EditCatchesUIModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -38,7 +38,7 @@ import fr.ifremer.tutti.ui.swing.util.AbstractTuttiBeanUIModel; import fr.ifremer.tutti.ui.swing.util.TabContentModel; import fr.ifremer.tutti.ui.swing.util.TuttiComputedOrNotData; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentModelAware; import org.apache.commons.collections.CollectionUtils; import org.nuiton.util.beans.Binder; @@ -237,11 +237,7 @@ Object oldObjectId = getObjectId(); super.fromEntity(entity); -// setCatchBatch(entity); -// Object oldValue = this.editObject; -// Object oldObjectId = getObjectId(); -// this.editObject = entity; firePropertyChange(PROPERTY_CATCH_BATCH, null, entity); firePropertyChange(PROPERTY_OBJECT_ID, oldObjectId, getObjectId()); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/SampleCategoryComponent.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/SampleCategoryComponent.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/SampleCategoryComponent.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,7 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategory; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import jaxx.runtime.JAXXUtil; import jaxx.runtime.swing.editor.NumberEditor; import org.nuiton.decorator.Decorator; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchRowModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchRowModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchRowModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -35,7 +35,7 @@ import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.ui.swing.util.AbstractTuttiBeanUIModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentModelAware; import fr.ifremer.tutti.ui.swing.util.caracteristics.CaracteristicMapColumnRowModel; import org.nuiton.util.beans.Binder; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchTableModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchTableModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchTableModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import fr.ifremer.tutti.ui.swing.content.operation.catches.individualobservation.IndividualObservationBatchRowModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableModel; import fr.ifremer.tutti.ui.swing.util.table.ColumnIdentifier; import org.jdesktop.swingx.table.TableColumnModelExt; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/accidental/AccidentalBatchUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -45,7 +45,7 @@ import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellEditor; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellRenderer; import fr.ifremer.tutti.ui.swing.util.caracteristics.CaracteristicMapCellComponent; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchRowModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchRowModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchRowModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -41,7 +41,7 @@ import fr.ifremer.tutti.ui.swing.util.AbstractTuttiBeanUIModel; import fr.ifremer.tutti.ui.swing.util.TuttiComputedOrNotData; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentModelAware; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.ObjectUtils; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchTableModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchTableModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchTableModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -29,7 +29,7 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.ui.swing.content.operation.catches.SampleCategoryColumnIdentifier; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableModel; import fr.ifremer.tutti.ui.swing.util.table.ColumnIdentifier; import org.apache.commons.logging.Log; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/BenthosBatchUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -36,12 +36,12 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategory; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocols; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.service.DecoratorService; import fr.ifremer.tutti.service.ValidationService; +import fr.ifremer.tutti.service.catches.ValidateCruiseOperationsService; import fr.ifremer.tutti.ui.swing.content.operation.AbstractTuttiBatchTableUIHandler; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUI; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUIHandler; @@ -59,7 +59,7 @@ import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellEditor; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellRenderer; import fr.ifremer.tutti.ui.swing.util.comment.CommentCellEditor; @@ -120,8 +120,10 @@ private final EnumMap<TableViewMode, RowFilter<BenthosBatchTableModel, Integer>> tableFilters; - protected ValidationService validationService = getContext().getValidationService(); + protected ValidationService validationService; + protected ValidateCruiseOperationsService validationCruiseService; + /** * Sample categories model. * @@ -198,6 +200,8 @@ return result; } }); + validationService = getContext().getValidationService(); + validationCruiseService = getContext().getValidateCruiseOperationsService(); } //------------------------------------------------------------------------// @@ -286,8 +290,7 @@ BenthosFrequencyRowModel.toEntity( row.getFrequency(), batch); - result = TuttiProtocols.isBenthosBatchValid( - getDataContext().getProtocol(), + result = validationCruiseService.isBenthosBatchValid( batch, frequencies); } Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/CreateBenthosMelagAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/CreateBenthosMelagAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/CreateBenthosMelagAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,7 @@ import com.google.common.collect.Maps; import fr.ifremer.tutti.ui.swing.content.operation.catches.benthos.frequency.BenthosFrequencyRowModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import fr.ifremer.tutti.ui.swing.util.species.EnterMelagWeightDialog; import jaxx.runtime.SwingUtil; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/ImportMultiPostAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/ImportMultiPostAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/ImportMultiPostAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import fr.ifremer.tutti.persistence.entities.data.BenthosBatch; import fr.ifremer.tutti.persistence.entities.data.CatchBatch; import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.service.catches.multipost.TuttiMultiPostImportService; +import fr.ifremer.tutti.service.catches.multipost.MultiPostImportService; import fr.ifremer.tutti.ui.swing.content.operation.catches.AbstractImportMultiPostAction; import fr.ifremer.tutti.ui.swing.content.operation.catches.MultiPostImportLogDialog; @@ -89,7 +89,7 @@ MultiPostImportLogDialog dialog = new MultiPostImportLogDialog((Dialog) getContext().getActionUI()); Collection<BenthosBatch> notImportedBenthosBatches = - (Collection<BenthosBatch>) notImportedData.get(TuttiMultiPostImportService.BATCHES_KEY); + (Collection<BenthosBatch>) notImportedData.get(MultiPostImportService.BATCHES_KEY); StringBuffer stringBuffer = new StringBuffer(); Float totalSortedWeight = (Float) notImportedData.get(CatchBatch.PROPERTY_BENTHOS_TOTAL_SORTED_WEIGHT); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/create/CreateBenthosBatchUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/create/CreateBenthosBatchUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/create/CreateBenthosBatchUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,16 +27,14 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; -import fr.ifremer.tutti.persistence.TuttiPersistence; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocols; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.service.DecoratorService; +import fr.ifremer.tutti.service.PersistenceService; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUI; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUIHandler; import fr.ifremer.tutti.ui.swing.content.operation.catches.benthos.BenthosBatchUI; @@ -46,7 +44,7 @@ import fr.ifremer.tutti.ui.swing.util.Cancelable; import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.species.SelectSpeciesUI; import fr.ifremer.tutti.ui.swing.util.species.SelectSpeciesUIModel; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableUIHandler; @@ -75,7 +73,7 @@ private static final Log log = LogFactory.getLog(CreateBenthosBatchUIHandler.class); - private final TuttiPersistence persistenceService; + private final PersistenceService persistenceService; /** * Qualitative value for the Vrac. @@ -282,8 +280,8 @@ if (getDataContext().isProtocolFilled()) { // try to find the first category from protocol - TuttiProtocol protocol = getDataContext().getProtocol(); - SpeciesProtocol speciesProtocol = TuttiProtocols.getBenthosProtocol(protocol, newValue); +// TuttiProtocol protocol = getDataContext().getProtocol(); + SpeciesProtocol speciesProtocol = persistenceService.getBenthosProtocol(newValue); if (speciesProtocol != null) { // species defined in protocol Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyRowModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyRowModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyRowModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -31,7 +31,7 @@ import fr.ifremer.tutti.persistence.entities.data.BenthosBatchFrequency; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.ui.swing.util.AbstractTuttiBeanUIModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import org.nuiton.util.beans.Binder; import org.nuiton.util.beans.BinderFactory; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyTableModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyTableModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyTableModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.collect.Maps; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableModel; import fr.ifremer.tutti.ui.swing.util.table.ColumnIdentifier; import org.jdesktop.swingx.table.TableColumnModelExt; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -24,14 +24,12 @@ * #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.tutti.persistence.entities.TuttiEntities; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.ui.swing.TuttiUIContext; @@ -42,7 +40,7 @@ import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractSelectTableAction; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableUIHandler; import jaxx.runtime.SwingUtil; @@ -83,7 +81,7 @@ private BenthosFrequencyCellComponent.FrequencyCellEditor frequencyEditor; - private TuttiProtocol protocol; +// private TuttiProtocol protocol; private Map<Integer, SpeciesProtocol> speciesProtocol; @@ -229,17 +227,22 @@ if (context.isProtocolFilled()) { - // get loaded protocol - protocol = getDataContext().getProtocol(); - Preconditions.checkNotNull(protocol, - "Could not find protocol in ui context"); +// // get loaded protocol +// protocol = getDataContext().getProtocol(); +// Preconditions.checkNotNull(protocol, +// "Could not find protocol in ui context"); // FIXME 20130128 kmorin: the species have no technical id + speciesProtocol = + getContext().getPersistenceService().toBenthosProtocolMap(); + +// speciesProtocol = Maps.newHashMap(); +// for (SpeciesProtocol sp : protocol.getBenthos()) { +// speciesProtocol.put(sp.getSpeciesReferenceTaxonId(), sp); +// } + + } else { speciesProtocol = Maps.newHashMap(); - for (SpeciesProtocol sp : protocol.getBenthos()) { - speciesProtocol.put(sp.getSpeciesReferenceTaxonId(), sp); - } - } Caracteristic modelCaracteristic = model.getLengthStepCaracteristic(); @@ -613,7 +616,8 @@ } } - if (lengthStepCaracteristic == null && protocol != null) { +// if (lengthStepCaracteristic == null && protocol != null) { + if (lengthStepCaracteristic == null) { Species species = speciesBatch.getSpecies(); @@ -645,7 +649,8 @@ } BenthosFrequencyUIModel.ConfigurationMode mode = BenthosFrequencyUIModel.ConfigurationMode.SIMPLE; - if (lengthStepCaracteristic == null && protocol != null) { +// if (lengthStepCaracteristic == null && protocol != null) { + if (lengthStepCaracteristic == null) { Integer taxonId = speciesBatch.getSpecies().getReferenceTaxonId(); SpeciesProtocol speciesProtocol = this.speciesProtocol.get(taxonId); if (speciesProtocol == null || speciesProtocol.getLengthStepPmfmId() == null) { Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyUIModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyUIModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/frequency/BenthosFrequencyUIModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -28,7 +28,7 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.ui.swing.content.operation.catches.benthos.BenthosBatchRowModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableUIModel; import java.util.List; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/split/SplitBenthosBatchUIModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/split/SplitBenthosBatchUIModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/benthos/split/SplitBenthosBatchUIModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -28,7 +28,7 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; import fr.ifremer.tutti.ui.swing.content.operation.catches.SelectedCategoryAble; import fr.ifremer.tutti.ui.swing.content.operation.catches.benthos.BenthosBatchRowModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableUIModel; import java.util.List; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchRowModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchRowModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchRowModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -32,7 +32,7 @@ import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.ui.swing.util.AbstractTuttiBeanUIModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentModelAware; import fr.ifremer.tutti.ui.swing.util.caracteristics.CaracteristicMapColumnRowModel; import org.nuiton.util.beans.Binder; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchTableModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchTableModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchTableModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -22,7 +22,7 @@ * #L% */ -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableModel; import fr.ifremer.tutti.ui.swing.util.table.ColumnIdentifier; import org.jdesktop.swingx.table.TableColumnModelExt; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/IndividualObservationBatchUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -43,7 +43,7 @@ import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellEditor; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellRenderer; import fr.ifremer.tutti.ui.swing.util.caracteristics.CaracteristicMapCellComponent; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/create/CreateIndividualObservationBatchUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/create/CreateIndividualObservationBatchUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/individualobservation/create/CreateIndividualObservationBatchUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -22,14 +22,11 @@ * #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.tutti.persistence.entities.TuttiEntities; import fr.ifremer.tutti.persistence.entities.data.IndividualObservationBatch; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; import fr.ifremer.tutti.persistence.entities.referential.Species; @@ -120,15 +117,13 @@ if (getDataContext().isProtocolFilled()) { - // get loaded protocol - TuttiProtocol protocol = getDataContext().getProtocol(); - Preconditions.checkNotNull(protocol, - "Could not find protocol in ui context"); +// // get loaded protocol +// TuttiProtocol protocol = getDataContext().getProtocol(); +// Preconditions.checkNotNull(protocol, +// "Could not find protocol in ui context"); - final Map<Integer, SpeciesProtocol> speciesProtocolMap = Maps.newHashMap(); - for (SpeciesProtocol sp : protocol.getSpecies()) { - speciesProtocolMap.put(sp.getSpeciesReferenceTaxonId(), sp); - } + final Map<Integer, SpeciesProtocol> speciesProtocolMap = + getContext().getPersistenceService().toSpeciesProtocolMap(); final Map<String, Caracteristic> lengthStepCaracteristicMap = TuttiEntities.splitById(lengthStepCaracteristics); @@ -236,7 +231,7 @@ } }); textField.addKeyListener(new KeyAdapter() { - + @Override public void keyReleased(KeyEvent e) { String value = textField.getText(); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/ImportMultiPostAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/ImportMultiPostAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/ImportMultiPostAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import fr.ifremer.tutti.persistence.entities.data.CatchBatch; import fr.ifremer.tutti.persistence.entities.data.FishingOperation; import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; -import fr.ifremer.tutti.service.catches.multipost.TuttiMultiPostImportService; +import fr.ifremer.tutti.service.catches.multipost.MultiPostImportService; import fr.ifremer.tutti.ui.swing.content.operation.catches.AbstractImportMultiPostAction; import fr.ifremer.tutti.ui.swing.content.operation.catches.MultiPostImportLogDialog; @@ -89,7 +89,7 @@ MultiPostImportLogDialog dialog = new MultiPostImportLogDialog((Dialog) getContext().getActionUI()); Collection<MarineLitterBatch> notImportedMarineLitterBatches = - (Collection<MarineLitterBatch>) notImportedData.get(TuttiMultiPostImportService.BATCHES_KEY); + (Collection<MarineLitterBatch>) notImportedData.get(MultiPostImportService.BATCHES_KEY); StringBuffer stringBuffer = new StringBuffer(); Float totalWeight = (Float) notImportedData.get(CatchBatch.PROPERTY_MARINE_LITTER_TOTAL_WEIGHT); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchRowModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchRowModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchRowModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -32,7 +32,7 @@ import fr.ifremer.tutti.persistence.entities.data.MarineLitterBatch; import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; import fr.ifremer.tutti.ui.swing.util.AbstractTuttiBeanUIModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentModelAware; import org.nuiton.util.beans.Binder; import org.nuiton.util.beans.BinderFactory; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchTableModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchTableModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchTableModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -24,7 +24,7 @@ * #L% */ -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableModel; import fr.ifremer.tutti.ui.swing.util.table.ColumnIdentifier; import org.jdesktop.swingx.table.TableColumnModelExt; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/marinelitter/MarineLitterBatchUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -43,7 +43,7 @@ import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellEditor; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellRenderer; import fr.ifremer.tutti.ui.swing.util.comment.CommentCellEditor; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/CreateSpeciesMelagAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/CreateSpeciesMelagAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/CreateSpeciesMelagAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,7 @@ import com.google.common.collect.Maps; import fr.ifremer.tutti.ui.swing.content.operation.catches.species.frequency.SpeciesFrequencyRowModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import fr.ifremer.tutti.ui.swing.util.species.EnterMelagWeightDialog; import jaxx.runtime.SwingUtil; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/ImportMultiPostAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/ImportMultiPostAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/ImportMultiPostAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import fr.ifremer.tutti.persistence.entities.data.CatchBatch; import fr.ifremer.tutti.persistence.entities.data.FishingOperation; import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.service.catches.multipost.TuttiMultiPostImportService; +import fr.ifremer.tutti.service.catches.multipost.MultiPostImportService; import fr.ifremer.tutti.ui.swing.content.operation.catches.AbstractImportMultiPostAction; import fr.ifremer.tutti.ui.swing.content.operation.catches.MultiPostImportLogDialog; @@ -89,7 +89,7 @@ MultiPostImportLogDialog dialog = new MultiPostImportLogDialog((Dialog) getContext().getActionUI()); Collection<SpeciesBatch> notImportedSpeciesBatches = - (Collection<SpeciesBatch>) notImportedData.get(TuttiMultiPostImportService.BATCHES_KEY); + (Collection<SpeciesBatch>) notImportedData.get(MultiPostImportService.BATCHES_KEY); StringBuffer stringBuffer = new StringBuffer(); Float totalSortedWeight = (Float) notImportedData.get(CatchBatch.PROPERTY_SPECIES_TOTAL_SORTED_WEIGHT); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/ImportPupitriAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/ImportPupitriAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/ImportPupitriAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -29,10 +29,9 @@ import fr.ifremer.tutti.persistence.entities.data.CatchBatch; import fr.ifremer.tutti.persistence.entities.data.FishingOperation; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.service.TuttiEnumerationFile; import fr.ifremer.tutti.service.PersistenceService; -import fr.ifremer.tutti.service.pupitri.TuttiPupitriImportExportService; +import fr.ifremer.tutti.service.pupitri.PupitriImportExportService; import fr.ifremer.tutti.ui.swing.content.operation.EditFishingOperationAction; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUIModel; import fr.ifremer.tutti.ui.swing.util.AbstractTuttiUIHandler; @@ -58,7 +57,7 @@ protected ImportPupitriPopupUI importPupitriDialog; - protected TuttiProtocol currentProtocol; +// protected TuttiProtocol currentProtocol; protected PersistenceService persistenceService; @@ -106,7 +105,7 @@ ); } if (result) { - currentProtocol = getDataContext().getProtocol(); +// currentProtocol = getDataContext().getProtocol(); SpeciesBatchUIModel speciesBatchUIModel = getUI().getModel(); if (speciesBatchUIModel.getRowCount() > 0) { @@ -138,7 +137,7 @@ @Override public void doAction() throws Exception { - TuttiPupitriImportExportService pupitriImportExportService = + PupitriImportExportService pupitriImportExportService = getContext().getTuttiPupitriImportExportService(); EditCatchesUIModel model = getUI().getHandler().getParentUi().getModel(); @@ -164,7 +163,7 @@ super.releaseAction(); importedTrunkFile = null; importedCarrouselFile = null; - currentProtocol = null; +// currentProtocol = null; } } Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchRowModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchRowModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchRowModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -41,7 +41,7 @@ import fr.ifremer.tutti.ui.swing.util.AbstractTuttiBeanUIModel; import fr.ifremer.tutti.ui.swing.util.TuttiComputedOrNotData; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentModelAware; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.ObjectUtils; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchTableModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchTableModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchTableModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -29,7 +29,7 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.ui.swing.content.operation.catches.SampleCategoryColumnIdentifier; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableModel; import fr.ifremer.tutti.ui.swing.util.table.ColumnIdentifier; import org.apache.commons.logging.Log; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/SpeciesBatchUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -36,12 +36,12 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocols; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.service.DecoratorService; import fr.ifremer.tutti.service.ValidationService; +import fr.ifremer.tutti.service.catches.ValidateCruiseOperationsService; import fr.ifremer.tutti.ui.swing.content.operation.AbstractTuttiBatchTableUIHandler; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUI; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUIHandler; @@ -58,7 +58,7 @@ import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellEditor; import fr.ifremer.tutti.ui.swing.util.attachment.AttachmentCellRenderer; import fr.ifremer.tutti.ui.swing.util.comment.CommentCellEditor; @@ -119,8 +119,10 @@ private final EnumMap<TableViewMode, RowFilter<SpeciesBatchTableModel, Integer>> tableFilters; - protected ValidationService validationService = getContext().getValidationService(); + protected ValidationService validationService; + protected ValidateCruiseOperationsService validationCruiseService; + protected final EditCatchesUI parentUi; /** @@ -200,6 +202,8 @@ return result; } }); + validationCruiseService = getContext().getValidateCruiseOperationsService(); + validationService = getContext().getValidationService(); } public EditCatchesUI getParentUi() { @@ -294,9 +298,9 @@ SpeciesFrequencyRowModel.toEntity( row.getFrequency(), batch); - result = TuttiProtocols.isSpeciesBatchValid(getDataContext().getProtocol(), - batch, - frequencies); + result = validationCruiseService.isSpeciesBatchValid( + batch, + frequencies); } return result; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/create/CreateSpeciesBatchUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/create/CreateSpeciesBatchUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/create/CreateSpeciesBatchUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,16 +27,14 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; -import fr.ifremer.tutti.persistence.TuttiPersistence; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocols; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.service.DecoratorService; +import fr.ifremer.tutti.service.PersistenceService; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUI; import fr.ifremer.tutti.ui.swing.content.operation.catches.EditCatchesUIHandler; import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SpeciesBatchUI; @@ -46,7 +44,7 @@ import fr.ifremer.tutti.ui.swing.util.Cancelable; import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.species.SelectSpeciesUI; import fr.ifremer.tutti.ui.swing.util.species.SelectSpeciesUIModel; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableUIHandler; @@ -76,7 +74,7 @@ private static final Log log = LogFactory.getLog(CreateSpeciesBatchUIHandler.class); - private final TuttiPersistence persistenceService; + private final PersistenceService persistenceService; /** * Qualitative value for the Vrac. @@ -286,8 +284,8 @@ log.info("Use protocol to find first category"); } // try to find the first category from protocol - TuttiProtocol protocol = getDataContext().getProtocol(); - SpeciesProtocol speciesProtocol = TuttiProtocols.getSpeciesProtocol(protocol, newValue); +// TuttiProtocol protocol = getDataContext().getProtocol(); + SpeciesProtocol speciesProtocol = persistenceService.getSpeciesProtocol(newValue); if (speciesProtocol != null) { if (log.isInfoEnabled()) { Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyRowModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyRowModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyRowModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -31,7 +31,7 @@ import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.ui.swing.util.AbstractTuttiBeanUIModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import org.nuiton.util.beans.Binder; import org.nuiton.util.beans.BinderFactory; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyTableModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyTableModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyTableModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.collect.Maps; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableModel; import fr.ifremer.tutti.ui.swing.util.table.ColumnIdentifier; import org.jdesktop.swingx.table.TableColumnModelExt; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -24,14 +24,11 @@ * #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.tutti.persistence.entities.TuttiEntities; import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.Species; import fr.ifremer.tutti.ui.swing.TuttiUIContext; @@ -43,7 +40,7 @@ import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractSelectTableAction; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableUIHandler; import jaxx.runtime.SwingUtil; @@ -84,7 +81,7 @@ private FrequencyCellEditor frequencyEditor; - private TuttiProtocol protocol; +// private TuttiProtocol protocol; private Map<Integer, SpeciesProtocol> speciesProtocol; @@ -227,16 +224,17 @@ if (context.isProtocolFilled()) { - // get loaded protocol - protocol = getDataContext().getProtocol(); - Preconditions.checkNotNull(protocol, - "Could not find protocol in ui context"); +// // get loaded protocol +// protocol = getDataContext().getProtocol(); +// Preconditions.checkNotNull(protocol, +// "Could not find protocol in ui context"); // FIXME 20130128 kmorin: the species have no technical id - speciesProtocol = Maps.newHashMap(); - for (SpeciesProtocol sp : protocol.getSpecies()) { - speciesProtocol.put(sp.getSpeciesReferenceTaxonId(), sp); - } + speciesProtocol = persistenceService.toSpeciesProtocolMap(); +// speciesProtocol = Maps.newHashMap(); +// for (SpeciesProtocol sp : protocol.getSpecies()) { +// speciesProtocol.put(sp.getSpeciesReferenceTaxonId(), sp); +// } } @@ -612,7 +610,8 @@ } } - if (lengthStepCaracteristic == null && protocol != null) { +// if (lengthStepCaracteristic == null && protocol != null) { + if (lengthStepCaracteristic == null) { Species species = speciesBatch.getSpecies(); @@ -644,7 +643,8 @@ } SpeciesFrequencyUIModel.ConfigurationMode mode = SpeciesFrequencyUIModel.ConfigurationMode.SIMPLE; - if (lengthStepCaracteristic == null && protocol != null) { +// if (lengthStepCaracteristic == null && protocol != null) { + if (lengthStepCaracteristic == null) { Integer taxonId = speciesBatch.getSpecies().getReferenceTaxonId(); SpeciesProtocol speciesProtocol = this.speciesProtocol.get(taxonId); if (speciesProtocol == null || speciesProtocol.getLengthStepPmfmId() == null) { Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyUIModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -28,7 +28,7 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModel; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SpeciesBatchRowModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableUIModel; import java.util.List; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/SplitSpeciesBatchUIModel.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/SplitSpeciesBatchUIModel.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/split/SplitSpeciesBatchUIModel.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -28,7 +28,7 @@ import fr.ifremer.tutti.persistence.entities.data.SampleCategoryModelEntry; import fr.ifremer.tutti.ui.swing.content.operation.catches.SelectedCategoryAble; import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SpeciesBatchRowModel; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.util.table.AbstractTuttiTableUIModel; import java.util.List; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/AbstractCaracteristicTabUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/AbstractCaracteristicTabUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/AbstractCaracteristicTabUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -30,7 +30,6 @@ import fr.ifremer.tutti.persistence.entities.CaracteristicMap; import fr.ifremer.tutti.persistence.entities.TuttiEntities; import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.ui.swing.content.operation.EditFishingOperationUI; import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor; @@ -166,7 +165,7 @@ protected abstract CaracteristicMap getCaracteristics(FishingOperation operation); - protected abstract List<String> getProtocolPmfmIds(TuttiProtocol protocol); + protected abstract List<String> getProtocolPmfmIds(); //------------------------------------------------------------------------// //-- Public methods --// @@ -204,10 +203,10 @@ } model.setCaracteristicMap(caracteristicMap); - TuttiProtocol protocol = getDataContext().getProtocol(); +// TuttiProtocol protocol = getDataContext().getProtocol(); List<String> pmfmIds = Lists.newArrayList(); - if (protocol != null) { - List<String> protocolPmfmId = getProtocolPmfmIds(protocol); + if (getDataContext().isProtocolFilled()) { + List<String> protocolPmfmId = getProtocolPmfmIds(); if (protocolPmfmId != null) { pmfmIds.addAll(protocolPmfmId); } Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/GearUseFeatureTabUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/GearUseFeatureTabUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/GearUseFeatureTabUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,6 @@ import fr.ifremer.tutti.persistence.entities.CaracteristicMap; import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.service.DecoratorService; import fr.ifremer.tutti.ui.swing.content.operation.EditFishingOperationUI; @@ -74,8 +73,8 @@ } @Override - protected List<String> getProtocolPmfmIds(TuttiProtocol protocol) { - return protocol.getGearUseFeaturePmfmId(); + protected List<String> getProtocolPmfmIds() { + return getDataContext().getProtocol().getGearUseFeaturePmfmId(); } //------------------------------------------------------------------------// Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/VesselUseFeatureTabUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/VesselUseFeatureTabUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/fishing/VesselUseFeatureTabUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,6 @@ import fr.ifremer.tutti.persistence.entities.CaracteristicMap; import fr.ifremer.tutti.persistence.entities.data.FishingOperation; -import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.service.DecoratorService; import fr.ifremer.tutti.ui.swing.content.operation.EditFishingOperationUI; @@ -74,8 +73,8 @@ } @Override - protected List<String> getProtocolPmfmIds(TuttiProtocol protocol) { - return protocol.getVesselUseFeaturePmfmId(); + protected List<String> getProtocolPmfmIds() { + return getDataContext().getProtocol().getVesselUseFeaturePmfmId(); } //------------------------------------------------------------------------// Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportAllCaracteristicAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportAllCaracteristicAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportAllCaracteristicAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -86,7 +86,7 @@ } // export protocol caracteristics - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); service.exportAllCaracteristic(file, getModel().getAllCaracteristic()); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolBenthosAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolBenthosAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolBenthosAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -100,7 +100,7 @@ } // import - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); service.exportProtocolBenthos(file, Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolCaracteristicAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolCaracteristicAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolCaracteristicAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,7 @@ import com.google.common.base.Preconditions; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -90,7 +90,7 @@ TuttiProtocol protocol = getModel().toBean(); // export protocol caracteristics - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); service.exportProtocolCaracteristic(file, Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolSpeciesAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolSpeciesAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportProtocolSpeciesAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -100,7 +100,7 @@ } // import - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); service.exportProtocolSpecies(file, Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportPupitriAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportPupitriAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ExportPupitriAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import fr.ifremer.tutti.persistence.entities.referential.Species; -import fr.ifremer.tutti.service.pupitri.TuttiPupitriImportExportService; +import fr.ifremer.tutti.service.pupitri.PupitriImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -101,7 +101,7 @@ } // import - TuttiPupitriImportExportService service = + PupitriImportExportService service = getContext().getTuttiPupitriImportExportService(); service.exportSpecies(speciesList, file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolBenthosAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolBenthosAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolBenthosAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import com.google.common.base.Preconditions; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -93,7 +93,7 @@ TuttiProtocol protocol = model.toBean(); // import - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); service.importProtocolBenthos(file, Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolCaracteristicAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolCaracteristicAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolCaracteristicAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -26,7 +26,7 @@ import com.google.common.base.Preconditions; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -90,7 +90,7 @@ // bind to a protocol TuttiProtocol protocol = model.toBean(); - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); service.importProtocolCaracteristic(file, Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolSpeciesAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolSpeciesAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/protocol/ImportProtocolSpeciesAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import com.google.common.base.Preconditions; import fr.ifremer.tutti.persistence.entities.protocol.SpeciesProtocol; import fr.ifremer.tutti.persistence.entities.protocol.TuttiProtocol; -import fr.ifremer.tutti.service.protocol.TuttiProtocolImportExportService; +import fr.ifremer.tutti.service.protocol.ProtocolImportExportService; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -93,7 +93,7 @@ TuttiProtocol protocol = model.toBean(); // import - TuttiProtocolImportExportService service = + ProtocolImportExportService service = getContext().getTuttiProtocolImportExportService(); service.importProtocolSpecies(file, Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryGearExampleAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryGearExampleAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryGearExampleAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -87,7 +87,7 @@ "referential to file: " + file); } - TuttiReferentialImportExportService service = + ReferentialImportExportService service = getContext().getTuttiReferentialImportExportService(); service.exportTemporaryGearExample(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryPersonExampleAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryPersonExampleAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryPersonExampleAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -88,7 +88,7 @@ "referential to file: " + file); } - TuttiReferentialImportExportService service = + ReferentialImportExportService service = getContext().getTuttiReferentialImportExportService(); service.exportTemporaryPersonExample(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporarySpeciesExampleAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporarySpeciesExampleAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporarySpeciesExampleAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -87,7 +87,7 @@ "referential to file: " + file); } - TuttiReferentialImportExportService service = + ReferentialImportExportService service = getContext().getTuttiReferentialImportExportService(); service.exportTemporarySpeciesExample(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryVesselExampleAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryVesselExampleAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ExportTemporaryVesselExampleAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -87,7 +87,7 @@ "referential to file: " + file); } - TuttiReferentialImportExportService service = + ReferentialImportExportService service = getContext().getTuttiReferentialImportExportService(); service.exportTemporaryVesselExample(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryGearAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryGearAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryGearAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -85,7 +85,7 @@ "referential from file: " + file); } - TuttiReferentialImportExportService service = + ReferentialImportExportService service = getContext().getTuttiReferentialImportExportService(); service.importTemporaryGear(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryPersonAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryPersonAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryPersonAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -85,7 +85,7 @@ "referential from file: " + file); } - TuttiReferentialImportExportService service = + ReferentialImportExportService service = getContext().getTuttiReferentialImportExportService(); service.importTemporaryPerson(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporarySpeciesAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporarySpeciesAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporarySpeciesAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -84,7 +84,7 @@ "referential from file: " + file); } - TuttiReferentialImportExportService service = + ReferentialImportExportService service = getContext().getTuttiReferentialImportExportService(); service.importTemporarySpecies(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryVesselAction.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryVesselAction.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/referential/ImportTemporaryVesselAction.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -25,7 +25,7 @@ */ import com.google.common.base.Preconditions; -import fr.ifremer.tutti.service.referential.TuttiReferentialImportExportService; +import fr.ifremer.tutti.service.referential.ReferentialImportExportService; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.util.action.AbstractTuttiAction; import org.apache.commons.logging.Log; @@ -84,7 +84,7 @@ "referential from file: " + file); } - TuttiReferentialImportExportService service = + ReferentialImportExportService service = getContext().getTuttiReferentialImportExportService(); service.importTemporaryVessel(file); Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/AbstractTuttiUIHandler.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/AbstractTuttiUIHandler.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/AbstractTuttiUIHandler.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -31,6 +31,7 @@ import fr.ifremer.tutti.persistence.entities.TuttiEntity; import fr.ifremer.tutti.service.DecoratorService; import fr.ifremer.tutti.service.TuttiDataContext; +import fr.ifremer.tutti.service.WeightUnit; import fr.ifremer.tutti.ui.swing.TuttiUIContext; import fr.ifremer.tutti.ui.swing.config.TuttiApplicationConfig; import fr.ifremer.tutti.ui.swing.content.MainUI; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/TuttiUI.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/TuttiUI.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/TuttiUI.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -24,6 +24,7 @@ * #L% */ +import fr.ifremer.tutti.service.WeightUnit; import jaxx.runtime.JAXXObject; import javax.swing.UIManager; @@ -103,7 +104,7 @@ * * @since 0.1 */ - public static final String DECIMAL1_PATTERN = "\\d{0,6}(\\.\\d{0,1})?"; + public static final String DECIMAL1_PATTERN = WeightUnit.G.getNumberEditorPattern(); /** * Pattern to use for decimal numeric values with 2 decimal digits in @@ -127,7 +128,7 @@ * * @since 2.6 */ - public static final String DECIMAL4_PATTERN = "\\d{0,6}(\\.\\d{0,4})?"; + public static final String DECIMAL4_PATTERN = WeightUnit.KG.getNumberEditorPattern(); /** * Pattern to use for decimal numeric values with 2 digits + 3 decimal digits in Deleted: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/WeightUnit.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/WeightUnit.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/WeightUnit.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -1,117 +0,0 @@ -package fr.ifremer.tutti.ui.swing.util; - -/* - * #%L - * Tutti :: UI - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2012 - 2013 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import static org.nuiton.i18n.I18n._; -import static org.nuiton.i18n.I18n.n_; - -/** - * Different types of weight unit. - * <p/> - * Created on 09/22/13. - * - * @author Tony Chemit <chemit@codelutin.com> - * @since 2.5 - */ -public enum WeightUnit { - G(n_("tutti.common.unit.g"), n_("tutti.common.unit.short.g"), 1, TuttiUI.DECIMAL1_PATTERN) { - @Override - public Float fromEntity(Float weight) { - return weight == null ? null : weight * 1000; - } - - @Override - public Float toEntity(Float weight) { - return weight == null ? null : weight / 1000.0f; - } - }, - KG(n_("tutti.common.unit.kg"), n_("tutti.common.unit.short.kg"), 4, TuttiUI.DECIMAL4_PATTERN) { - @Override - public Float fromEntity(Float weight) { - return weight; - } - - @Override - public Float toEntity(Float weight) { - return weight; - } - }; - - private final String i18nShortKey; - - private final String i18nKey; - - private final int numberDigits; - - private final String numberEditorPattern; - - WeightUnit(String i18nKey, String i18nShortKey, int numberDigits, String numberEditorPattern) { - this.i18nKey = i18nKey; - this.i18nShortKey = i18nShortKey; - this.numberDigits = numberDigits; - this.numberEditorPattern = numberEditorPattern; - } - - public String getLabel() { - return _(i18nKey); - } - - public String getShortLabel() { - return _(i18nShortKey); - } - - public int getNumberDigits() { - return numberDigits; - } - - public String getNumberEditorPattern() { - return numberEditorPattern; - } - - /** - * Transform the given {@code weight} coming from db to ui. - * - * @param weight weigth to transform - * @return the ui representation of the given {@code weight}. - */ - public abstract Float fromEntity(Float weight); - - /** - * Transform the given {@code weight} coming from ui to db. - * - * @param weight weigth to transform - * @return the db representation of the given {@code weight}. - */ - public abstract Float toEntity(Float weight); - - public String decorateLabel(String label) { - return String.format("%s (%s)", label, getShortLabel()); - } - - public String decorateTip(String tip) { - String unit = _("tutti.common.unit"); - return String.format("%s (%s %s)", tip, unit, getLabel()); - } -} Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataTableCell.java =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataTableCell.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataTableCell.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -27,7 +27,7 @@ import fr.ifremer.tutti.ui.swing.util.TuttiComputedOrNotData; import fr.ifremer.tutti.ui.swing.util.TuttiUI; import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil; -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import jaxx.runtime.JAXXUtil; import javax.swing.AbstractCellEditor; Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/species/EnterMelagWeightDialog.jaxx =================================================================== --- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/species/EnterMelagWeightDialog.jaxx 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/species/EnterMelagWeightDialog.jaxx 2013-09-28 12:15:25 UTC (rev 1247) @@ -23,7 +23,7 @@ --> <JDialog id='dialog' layout='{new BorderLayout()}'> <import> - fr.ifremer.tutti.ui.swing.util.WeightUnit + fr.ifremer.tutti.service.WeightUnit java.awt.Component; java.awt.event.WindowAdapter; Modified: trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_en_GB.properties =================================================================== --- trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_en_GB.properties 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_en_GB.properties 2013-09-28 12:15:25 UTC (rev 1247) @@ -493,8 +493,21 @@ tutti.editCatchBatch.action.cancelEditCatchBatch= tutti.editCatchBatch.action.cancelEditCatchBatch.mnemonic= tutti.editCatchBatch.action.cancelEditCatchBatch.tip= +tutti.editCatchBatch.action.cleanWeights= +tutti.editCatchBatch.action.cleanWeights.done= +tutti.editCatchBatch.action.cleanWeights.double.weight.detected= +tutti.editCatchBatch.action.cleanWeights.errors.found= +tutti.editCatchBatch.action.cleanWeights.help= +tutti.editCatchBatch.action.cleanWeights.mnemonic= +tutti.editCatchBatch.action.cleanWeights.no.double.weight.detected= +tutti.editCatchBatch.action.cleanWeights.no.weight.to.remove= +tutti.editCatchBatch.action.cleanWeights.tip= +tutti.editCatchBatch.action.cleanWieghts.resume.title= tutti.editCatchBatch.action.computeWeights= +tutti.editCatchBatch.action.computeWeights.double.weight.detected= +tutti.editCatchBatch.action.computeWeights.double.weight.detected.title= tutti.editCatchBatch.action.computeWeights.mnemonic= +tutti.editCatchBatch.action.computeWeights.no.double.weight.detected= tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.help= tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.message.benthos= tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.message.species= Modified: trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties =================================================================== --- trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-09-28 12:15:25 UTC (rev 1247) @@ -494,8 +494,19 @@ tutti.editCatchBatch.action.cancelEditCatchBatch=Réinitialiser tutti.editCatchBatch.action.cancelEditCatchBatch.mnemonic=R tutti.editCatchBatch.action.cancelEditCatchBatch.tip=Réinitialiser l'édition de la capture +tutti.editCatchBatch.action.cleanWeights=Supprimer les poids +tutti.editCatchBatch.action.cleanWeights.done=%s poids en double ont été supprimés. +tutti.editCatchBatch.action.cleanWeights.double.weight.detected=Des poids en doubles ont été detéctés \: %s +tutti.editCatchBatch.action.cleanWeights.help=Que voulez-vous faire?<ul><li><strong>Annuler</strong> pour ne rien faire</li><li><strong>Ok</strong> pour enregister les modifications</li></ul> +tutti.editCatchBatch.action.cleanWeights.mnemonic=S +tutti.editCatchBatch.action.cleanWeights.no.double.weight.detected=Aucun poids en double détecté. +tutti.editCatchBatch.action.cleanWeights.tip=Supprimer les poids superflus dans les captures espèces et benthos +tutti.editCatchBatch.action.cleanWieghts.resume.title=Confirmer la suppression des poids en double tutti.editCatchBatch.action.computeWeights=Élever les poids +tutti.editCatchBatch.action.computeWeights.double.weight.detected=<html><body>Des poids en doubles ont été detéctés \: %s</body></html> +tutti.editCatchBatch.action.computeWeights.double.weight.detected.title=Poids en double détectés tutti.editCatchBatch.action.computeWeights.mnemonic=p +tutti.editCatchBatch.action.computeWeights.no.double.weight.detected=Aucun poids en double détecté. tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.help=Est-ce bien une valeur observée ?<ul><li><strong>Non</strong> pour remplacer la valeur saisie par le poids calculé</li><li><strong>Oui</strong> pour garder la valeur saisie</li></ul>. tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.message.benthos=Le Poids total VRAC saisi sur le benthos est supérieur de moins de %s%% au Poids total Vrac trié. tutti.editCatchBatch.action.computeWeights.replaceTotalSortedWeight.message.species=Le Poids total VRAC saisi sur les espèces est supérieur de moins de %s%% au Poids total Vrac trié. Modified: trunk/tutti-ui-swing/src/test/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyRowModelTest.java =================================================================== --- trunk/tutti-ui-swing/src/test/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyRowModelTest.java 2013-09-27 16:12:11 UTC (rev 1246) +++ trunk/tutti-ui-swing/src/test/java/fr/ifremer/tutti/ui/swing/content/operation/catches/species/frequency/SpeciesFrequencyRowModelTest.java 2013-09-28 12:15:25 UTC (rev 1247) @@ -24,7 +24,7 @@ * #L% */ -import fr.ifremer.tutti.ui.swing.util.WeightUnit; +import fr.ifremer.tutti.service.WeightUnit; import org.junit.Assert; import org.junit.Test;