branch develop updated (e4c7528 -> 25dd1bb)
This is an automated email from the git hooks/post-receive script. New change to branch develop in repository observe. See https://gitlab.nuiton.org/codelutin/observe.git from e4c7528 Revue du code relatif au gps et suppression du code en double (entités vs service model) new 25dd1bb suppression du moduel business The 1 revisions listed above as "new" are entirely new to this repository and will be described in separate emails. The revisions listed as "adds" were already present in the repository and have only been added to this reference. Detailed log of new commits: commit 25dd1bbcc6218ee6d1c96c33b5d4ecb4b45a9d64 Author: Tony CHEMIT <chemit@codelutin.com> Date: Mon Aug 1 17:17:37 2016 +0200 suppression du moduel business Summary of changes: observe-business/LICENSE.txt | 674 ----- observe-business/README.md | 2 - observe-business/changelog.txt | 2 - observe-business/pom.xml | 413 ---- .../src/license/THIRD-PARTY.properties | 30 - .../src/main/filters/observe-reports.properties | 854 ------- .../main/java/fr/ird/converter/FloatConverter.java | 87 - .../main/java/fr/ird/observe/BinderService.java | 71 - .../fr/ird/observe/ConsolidateDataService.java | 883 ------- .../src/main/java/fr/ird/observe/DataService.java | 2606 -------------------- .../main/java/fr/ird/observe/DecoratorService.java | 611 ----- .../main/java/fr/ird/observe/IObserveConfig.java | 412 ---- .../fr/ird/observe/ObserveApplicationContext.java | 224 -- .../java/fr/ird/observe/ObserveServiceHelper.java | 331 --- .../fr/ird/observe/ObserveTechnicalException.java | 50 - .../main/java/fr/ird/observe/SendMessageAble.java | 33 - .../main/java/fr/ird/observe/db/DataContext.java | 702 ------ .../main/java/fr/ird/observe/db/DataSource.java | 232 -- .../java/fr/ird/observe/db/DataSourceConfig.java | 219 -- .../fr/ird/observe/db/DataSourceConfigParam.java | 43 - .../fr/ird/observe/db/DataSourceException.java | 55 - .../java/fr/ird/observe/db/DataSourceFactory.java | 456 ---- .../java/fr/ird/observe/db/DataSourceProvider.java | 73 - .../java/fr/ird/observe/db/ReplicationService.java | 374 --- .../java/fr/ird/observe/db/VoidTopiaEntity.java | 34 - .../db/constants/CommonDataSourceConfigParam.java | 127 - .../ird/observe/db/constants/ConnexionStatus.java | 66 - .../fr/ird/observe/db/constants/CreationMode.java | 82 - .../ird/observe/db/constants/DataContextType.java | 328 --- .../fr/ird/observe/db/constants/DataPolicy.java | 72 - .../ird/observe/db/constants/DataSourceState.java | 40 - .../java/fr/ird/observe/db/constants/DbMode.java | 65 - .../fr/ird/observe/db/event/DataSourceEvent.java | 83 - .../ird/observe/db/event/DataSourceListener.java | 75 - .../db/event/DataSourceListenerAdapter.java | 56 - .../fr/ird/observe/db/impl/AbstractDataSource.java | 863 ------- .../observe/db/impl/AbstractDataSourceConfig.java | 415 ---- .../db/impl/AbstractDataSourceProvider.java | 358 --- .../java/fr/ird/observe/db/impl/H2DataSource.java | 155 -- .../fr/ird/observe/db/impl/H2DataSourceConfig.java | 247 -- .../observe/db/impl/H2DataSourceConfigParam.java | 100 - .../ird/observe/db/impl/H2DataSourceProvider.java | 65 - .../java/fr/ird/observe/db/impl/PGDataSource.java | 175 -- .../fr/ird/observe/db/impl/PGDataSourceConfig.java | 470 ---- .../observe/db/impl/PGDataSourceConfigParam.java | 81 - .../ird/observe/db/impl/PGDataSourceProvider.java | 44 - .../main/java/fr/ird/observe/db/package-info.java | 30 - .../java/fr/ird/observe/db/util/PGInstall.java | 555 ----- .../java/fr/ird/observe/db/util/SecurityModel.java | 217 -- .../java/fr/ird/observe/db/util/TopiaExecutor.java | 38 - .../fr/ird/observe/db/util/TopiaExecutor2.java | 39 - .../decorator/LengthWeightParameterDecorator.java | 89 - .../observe/decorator/NonTargetCatchDecorator.java | 56 - .../decorator/NonTargetLengthDecorator.java | 63 - .../decorator/ObjectObservedSpeciesDecorator.java | 54 - .../fr/ird/observe/decorator/ObserveDecorator.java | 91 - .../ird/observe/decorator/ReferenceDecorator.java | 48 - .../fr/ird/observe/decorator/SpeciesDecorator.java | 71 - .../observe/decorator/TripLonglineDecorator.java | 42 - .../ird/observe/decorator/TripSeineDecorator.java | 42 - .../java/fr/ird/observe/gps/GPSFileReader.java | 356 --- .../main/java/fr/ird/observe/gps/GPSService.java | 115 - .../java/fr/ird/observe/report/ReportBuilder.java | 490 ---- .../fr/ird/observe/report/model/DataMatrix.java | 259 -- .../java/fr/ird/observe/report/model/Report.java | 144 -- .../fr/ird/observe/report/model/ReportExecute.java | 297 --- .../ird/observe/report/model/ReportOperation.java | 112 - .../fr/ird/observe/report/model/ReportRequest.java | 371 --- .../ird/observe/report/model/ReportVariable.java | 59 - .../report/model/operations/ExecuteRequests.java | 131 - .../report/model/operations/GroupByLength.java | 109 - .../observe/report/model/operations/SumColumn.java | 132 - .../report/model/operations/SumIntColumn.java | 132 - .../observe/report/model/operations/SumIntRow.java | 132 - .../observe/report/model/operations/SumRow.java | 132 - .../java/fr/ird/observe/report/package-info.java | 30 - .../main/java/fr/ird/observe/test/TestHelper.java | 148 -- .../src/main/java/fr/ird/observe/util/Scripts.java | 168 -- .../ird/observe/validation/ObserveValidator.java | 185 -- .../ird/observe/validation/ValidationContext.java | 301 --- .../validation/ValidationMessageDetector.java | 559 ----- .../observe/validation/ValidationModelMode.java | 85 - .../ird/observe/validation/ValidationService.java | 155 -- .../fr/ird/observe/validation/ValidatorsMap.java | 121 - .../fr.ird.observe.business.db.DataSourceProvider | 2 - .../fr.ird.observe.report.model.ReportOperation | 6 - .../src/main/resources/faunaminmax.csv | 164 -- .../i18n/observe-business_en_GB.properties | 234 -- .../i18n/observe-business_es_ES.properties | 234 -- .../i18n/observe-business_fr_FR.properties | 234 -- .../src/main/resources/observe-ehcache.xml | 49 - observe-business/src/main/resources/xwork.xml | 30 - .../java/fr/ird/converter/FloatConverterTest.java | 78 - .../java/fr/ird/observe/EntityDetectorTest.java | 336 --- .../test/java/fr/ird/observe/db/DBTestHelper.java | 604 ----- .../java/fr/ird/observe/db/DataServiceTest.java | 338 --- .../fr/ird/observe/db/DataSourceFactoryTest.java | 84 - .../fr/ird/observe/db/ReplicationServiceTest.java | 297 --- .../observe/db/impl/H2DataSourceConfigTest.java | 249 -- .../observe/db/impl/PGDataSourceConfigTest.java | 300 --- .../java/fr/ird/observe/gps/GPSFileReaderTest.java | 187 -- .../test/java/fr/ird/observe/gps/GPSRouteTest.java | 162 -- .../java/fr/ird/observe/gps/GPSServiceTest.java | 94 - .../fr/ird/observe/its/DataSourceFactoryIT.java | 323 --- .../test/java/fr/ird/observe/its/PGInstallIT.java | 172 -- .../java/fr/ird/observe/its/RestoreEmptyPGIT.java | 81 - .../migration/AbstractDataSourceMigrationTest.java | 67 - .../its/migration/AbstractMigrationTest.java | 139 -- .../its/migration/H2DataSourceMigrationIT.java | 390 --- .../its/migration/PGDataSourceMigrationIT.java | 140 -- .../h2ToLast/AbstractH2MigrationToLastIT.java | 114 - .../its/migration/h2ToLast/MigrationV4_0IT.java | 48 - .../its/replication/AbstractReplicateDataTest.java | 417 ---- .../AbstractReplicateReferentielTest.java | 269 -- .../its/replication/AbstractReplicateTest.java | 88 - .../observe/its/replication/H2ReplicateDataIT.java | 69 - .../its/replication/H2ReplicateDataTest.java | 370 --- .../its/replication/H2ReplicateReferentielIT.java | 60 - .../observe/its/replication/PGReplicateDataIT.java | 75 - .../its/replication/PGReplicateReferentielIT.java | 57 - .../its/replication/ReplicationDataModel.java | 170 -- .../ird/observe/its/report/AbstractReportIT.java | 290 --- .../its/report/accessoryCatch/Report2IT.java | 51 - .../its/report/accessoryCatch/ReportIT.java | 105 - .../report/accessoryCatchByGroup/Report2IT.java | 51 - .../its/report/accessoryCatchByGroup/ReportIT.java | 154 -- .../its/report/activityWithComment/ReportIT.java | 81 - .../observe/its/report/allActivitys/ReportIT.java | 79 - .../its/report/dailySetAndCatch/ReportIT.java | 96 - .../ird/observe/its/report/dcpUsage/ReportIT.java | 135 - .../its/report/setByAssociation/Report2IT.java | 52 - .../its/report/setByAssociation/ReportIT.java | 124 - .../report/targetCatchByAssociation/ReportIT.java | 94 - .../targetDiscardedByAssociation/ReportIT.java | 94 - .../observe/validation/ValidationServiceTest.java | 517 ---- .../src/test/resources/db/4.0.2/referentiel.sql.gz | Bin 138257 -> 0 bytes .../referentiel/Ocean-test3-error-validation.xml | 32 - .../referentiel/Program-test1-error-validation.xml | 32 - .../referentiel/Program-test3-info-validation.xml | 32 - .../seine/TripSeine-test2-error-validation.xml | 31 - .../seine/TripSeine-test3-warning-validation.xml | 31 - .../resources/fr/ird/observe/gps/GL50_13_small.gpx | 167 -- .../ird/observe/gps/testInterval_allAccepted.gpx | 157 -- .../ird/observe/gps/testInterval_allRejected.gpx | 157 -- .../gps/testInterval_firtPointsRejected.gpx | 157 -- .../gps/testInterval_insidePointsRejected.gpx | 157 -- .../gps/testInterval_insidePointsRejected2.gpx | 157 -- .../gps/testInterval_lastPointsRejected.gpx | 157 -- .../src/test/resources/log4j.properties | 33 - .../resources/reports/accessoryCatchByGroup.sql.gz | Bin 107164 -> 0 bytes .../resources/reports/activityWithComment.sql.gz | Bin 106335 -> 0 bytes .../src/test/resources/reports/allActivitys.sql.gz | Bin 106335 -> 0 bytes .../test/resources/reports/dailySetAndCatch.sql.gz | Bin 108462 -> 0 bytes .../src/test/resources/reports/dcpUsage.sql.gz | Bin 106816 -> 0 bytes .../test/resources/reports/setByAssociation.sql.gz | Bin 107630 -> 0 bytes .../resources/reports/setByAssociation2.sql.gz | Bin 109225 -> 0 bytes .../reports/targetCatchByAssociation.sql.gz | Bin 108732 -> 0 bytes .../reports/targetDiscardedByAssociation.sql.gz | Bin 108725 -> 0 bytes 158 files changed, 29550 deletions(-) delete mode 100644 observe-business/LICENSE.txt delete mode 100644 observe-business/README.md delete mode 100644 observe-business/changelog.txt delete mode 100644 observe-business/pom.xml delete mode 100644 observe-business/src/license/THIRD-PARTY.properties delete mode 100644 observe-business/src/main/filters/observe-reports.properties delete mode 100644 observe-business/src/main/java/fr/ird/converter/FloatConverter.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/BinderService.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/ConsolidateDataService.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/DataService.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/DecoratorService.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/IObserveConfig.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/ObserveApplicationContext.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/ObserveServiceHelper.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/ObserveTechnicalException.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/SendMessageAble.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/DataContext.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/DataSource.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/DataSourceConfig.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/DataSourceConfigParam.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/DataSourceException.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/DataSourceFactory.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/DataSourceProvider.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/VoidTopiaEntity.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/constants/CommonDataSourceConfigParam.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/constants/ConnexionStatus.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/constants/CreationMode.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/constants/DataContextType.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/constants/DataPolicy.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/constants/DataSourceState.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/constants/DbMode.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/event/DataSourceEvent.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/event/DataSourceListener.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/event/DataSourceListenerAdapter.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSource.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSourceConfig.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSourceProvider.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSource.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceConfig.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceConfigParam.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceProvider.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSource.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceConfig.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceConfigParam.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceProvider.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/package-info.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/util/PGInstall.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/util/SecurityModel.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/util/TopiaExecutor.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/db/util/TopiaExecutor2.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/LengthWeightParameterDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/NonTargetCatchDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/NonTargetLengthDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/ObjectObservedSpeciesDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/ObserveDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/ReferenceDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/SpeciesDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/TripLonglineDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/decorator/TripSeineDecorator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/gps/GPSFileReader.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/gps/GPSService.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/ReportBuilder.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/DataMatrix.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/Report.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/ReportExecute.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/ReportOperation.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/ReportRequest.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/ReportVariable.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/operations/ExecuteRequests.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/operations/GroupByLength.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/operations/SumColumn.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/operations/SumIntColumn.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/operations/SumIntRow.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/model/operations/SumRow.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/report/package-info.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/test/TestHelper.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/util/Scripts.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/validation/ObserveValidator.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/validation/ValidationContext.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/validation/ValidationMessageDetector.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/validation/ValidationModelMode.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/validation/ValidationService.java delete mode 100644 observe-business/src/main/java/fr/ird/observe/validation/ValidatorsMap.java delete mode 100644 observe-business/src/main/resources/META-INF/services/fr.ird.observe.business.db.DataSourceProvider delete mode 100644 observe-business/src/main/resources/META-INF/services/fr.ird.observe.report.model.ReportOperation delete mode 100644 observe-business/src/main/resources/faunaminmax.csv delete mode 100644 observe-business/src/main/resources/i18n/observe-business_en_GB.properties delete mode 100644 observe-business/src/main/resources/i18n/observe-business_es_ES.properties delete mode 100644 observe-business/src/main/resources/i18n/observe-business_fr_FR.properties delete mode 100644 observe-business/src/main/resources/observe-ehcache.xml delete mode 100644 observe-business/src/main/resources/xwork.xml delete mode 100644 observe-business/src/test/java/fr/ird/converter/FloatConverterTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/EntityDetectorTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/db/DBTestHelper.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/db/DataServiceTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/db/DataSourceFactoryTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/db/ReplicationServiceTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/db/impl/H2DataSourceConfigTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/db/impl/PGDataSourceConfigTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/gps/GPSFileReaderTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/gps/GPSRouteTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/gps/GPSServiceTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/DataSourceFactoryIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/PGInstallIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/RestoreEmptyPGIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/migration/AbstractDataSourceMigrationTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/migration/AbstractMigrationTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/migration/H2DataSourceMigrationIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/migration/PGDataSourceMigrationIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/migration/h2ToLast/AbstractH2MigrationToLastIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/migration/h2ToLast/MigrationV4_0IT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateDataTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateReferentielTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateDataIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateDataTest.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateReferentielIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/PGReplicateDataIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/PGReplicateReferentielIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/replication/ReplicationDataModel.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/AbstractReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatch/Report2IT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatch/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatchByGroup/Report2IT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatchByGroup/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/activityWithComment/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/allActivitys/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/dailySetAndCatch/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/dcpUsage/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/setByAssociation/Report2IT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/setByAssociation/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/targetCatchByAssociation/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/its/report/targetDiscardedByAssociation/ReportIT.java delete mode 100644 observe-business/src/test/java/fr/ird/observe/validation/ValidationServiceTest.java delete mode 100644 observe-business/src/test/resources/db/4.0.2/referentiel.sql.gz delete mode 100644 observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Ocean-test3-error-validation.xml delete mode 100644 observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Program-test1-error-validation.xml delete mode 100644 observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Program-test3-info-validation.xml delete mode 100644 observe-business/src/test/resources/fr/ird/observe/entities/seine/TripSeine-test2-error-validation.xml delete mode 100644 observe-business/src/test/resources/fr/ird/observe/entities/seine/TripSeine-test3-warning-validation.xml delete mode 100644 observe-business/src/test/resources/fr/ird/observe/gps/GL50_13_small.gpx delete mode 100644 observe-business/src/test/resources/fr/ird/observe/gps/testInterval_allAccepted.gpx delete mode 100644 observe-business/src/test/resources/fr/ird/observe/gps/testInterval_allRejected.gpx delete mode 100644 observe-business/src/test/resources/fr/ird/observe/gps/testInterval_firtPointsRejected.gpx delete mode 100644 observe-business/src/test/resources/fr/ird/observe/gps/testInterval_insidePointsRejected.gpx delete mode 100644 observe-business/src/test/resources/fr/ird/observe/gps/testInterval_insidePointsRejected2.gpx delete mode 100644 observe-business/src/test/resources/fr/ird/observe/gps/testInterval_lastPointsRejected.gpx delete mode 100644 observe-business/src/test/resources/log4j.properties delete mode 100644 observe-business/src/test/resources/reports/accessoryCatchByGroup.sql.gz delete mode 100644 observe-business/src/test/resources/reports/activityWithComment.sql.gz delete mode 100644 observe-business/src/test/resources/reports/allActivitys.sql.gz delete mode 100644 observe-business/src/test/resources/reports/dailySetAndCatch.sql.gz delete mode 100644 observe-business/src/test/resources/reports/dcpUsage.sql.gz delete mode 100644 observe-business/src/test/resources/reports/setByAssociation.sql.gz delete mode 100644 observe-business/src/test/resources/reports/setByAssociation2.sql.gz delete mode 100644 observe-business/src/test/resources/reports/targetCatchByAssociation.sql.gz delete mode 100644 observe-business/src/test/resources/reports/targetDiscardedByAssociation.sql.gz -- To stop receiving notification emails like this one, please contact codelutin.com SCM administrator <admin+scm@codelutin.com>.
This is an automated email from the git hooks/post-receive script. New commit to branch develop in repository observe. See https://gitlab.nuiton.org/codelutin/observe.git commit 25dd1bbcc6218ee6d1c96c33b5d4ecb4b45a9d64 Author: Tony CHEMIT <chemit@codelutin.com> Date: Mon Aug 1 17:17:37 2016 +0200 suppression du moduel business --- observe-business/LICENSE.txt | 674 ----- observe-business/README.md | 2 - observe-business/changelog.txt | 2 - observe-business/pom.xml | 413 ---- .../src/license/THIRD-PARTY.properties | 30 - .../src/main/filters/observe-reports.properties | 854 ------- .../main/java/fr/ird/converter/FloatConverter.java | 87 - .../main/java/fr/ird/observe/BinderService.java | 71 - .../fr/ird/observe/ConsolidateDataService.java | 883 ------- .../src/main/java/fr/ird/observe/DataService.java | 2606 -------------------- .../main/java/fr/ird/observe/DecoratorService.java | 611 ----- .../main/java/fr/ird/observe/IObserveConfig.java | 412 ---- .../fr/ird/observe/ObserveApplicationContext.java | 224 -- .../java/fr/ird/observe/ObserveServiceHelper.java | 331 --- .../fr/ird/observe/ObserveTechnicalException.java | 50 - .../main/java/fr/ird/observe/SendMessageAble.java | 33 - .../main/java/fr/ird/observe/db/DataContext.java | 702 ------ .../main/java/fr/ird/observe/db/DataSource.java | 232 -- .../java/fr/ird/observe/db/DataSourceConfig.java | 219 -- .../fr/ird/observe/db/DataSourceConfigParam.java | 43 - .../fr/ird/observe/db/DataSourceException.java | 55 - .../java/fr/ird/observe/db/DataSourceFactory.java | 456 ---- .../java/fr/ird/observe/db/DataSourceProvider.java | 73 - .../java/fr/ird/observe/db/ReplicationService.java | 374 --- .../java/fr/ird/observe/db/VoidTopiaEntity.java | 34 - .../db/constants/CommonDataSourceConfigParam.java | 127 - .../ird/observe/db/constants/ConnexionStatus.java | 66 - .../fr/ird/observe/db/constants/CreationMode.java | 82 - .../ird/observe/db/constants/DataContextType.java | 328 --- .../fr/ird/observe/db/constants/DataPolicy.java | 72 - .../ird/observe/db/constants/DataSourceState.java | 40 - .../java/fr/ird/observe/db/constants/DbMode.java | 65 - .../fr/ird/observe/db/event/DataSourceEvent.java | 83 - .../ird/observe/db/event/DataSourceListener.java | 75 - .../db/event/DataSourceListenerAdapter.java | 56 - .../fr/ird/observe/db/impl/AbstractDataSource.java | 863 ------- .../observe/db/impl/AbstractDataSourceConfig.java | 415 ---- .../db/impl/AbstractDataSourceProvider.java | 358 --- .../java/fr/ird/observe/db/impl/H2DataSource.java | 155 -- .../fr/ird/observe/db/impl/H2DataSourceConfig.java | 247 -- .../observe/db/impl/H2DataSourceConfigParam.java | 100 - .../ird/observe/db/impl/H2DataSourceProvider.java | 65 - .../java/fr/ird/observe/db/impl/PGDataSource.java | 175 -- .../fr/ird/observe/db/impl/PGDataSourceConfig.java | 470 ---- .../observe/db/impl/PGDataSourceConfigParam.java | 81 - .../ird/observe/db/impl/PGDataSourceProvider.java | 44 - .../main/java/fr/ird/observe/db/package-info.java | 30 - .../java/fr/ird/observe/db/util/PGInstall.java | 555 ----- .../java/fr/ird/observe/db/util/SecurityModel.java | 217 -- .../java/fr/ird/observe/db/util/TopiaExecutor.java | 38 - .../fr/ird/observe/db/util/TopiaExecutor2.java | 39 - .../decorator/LengthWeightParameterDecorator.java | 89 - .../observe/decorator/NonTargetCatchDecorator.java | 56 - .../decorator/NonTargetLengthDecorator.java | 63 - .../decorator/ObjectObservedSpeciesDecorator.java | 54 - .../fr/ird/observe/decorator/ObserveDecorator.java | 91 - .../ird/observe/decorator/ReferenceDecorator.java | 48 - .../fr/ird/observe/decorator/SpeciesDecorator.java | 71 - .../observe/decorator/TripLonglineDecorator.java | 42 - .../ird/observe/decorator/TripSeineDecorator.java | 42 - .../java/fr/ird/observe/gps/GPSFileReader.java | 356 --- .../main/java/fr/ird/observe/gps/GPSService.java | 115 - .../java/fr/ird/observe/report/ReportBuilder.java | 490 ---- .../fr/ird/observe/report/model/DataMatrix.java | 259 -- .../java/fr/ird/observe/report/model/Report.java | 144 -- .../fr/ird/observe/report/model/ReportExecute.java | 297 --- .../ird/observe/report/model/ReportOperation.java | 112 - .../fr/ird/observe/report/model/ReportRequest.java | 371 --- .../ird/observe/report/model/ReportVariable.java | 59 - .../report/model/operations/ExecuteRequests.java | 131 - .../report/model/operations/GroupByLength.java | 109 - .../observe/report/model/operations/SumColumn.java | 132 - .../report/model/operations/SumIntColumn.java | 132 - .../observe/report/model/operations/SumIntRow.java | 132 - .../observe/report/model/operations/SumRow.java | 132 - .../java/fr/ird/observe/report/package-info.java | 30 - .../main/java/fr/ird/observe/test/TestHelper.java | 148 -- .../src/main/java/fr/ird/observe/util/Scripts.java | 168 -- .../ird/observe/validation/ObserveValidator.java | 185 -- .../ird/observe/validation/ValidationContext.java | 301 --- .../validation/ValidationMessageDetector.java | 559 ----- .../observe/validation/ValidationModelMode.java | 85 - .../ird/observe/validation/ValidationService.java | 155 -- .../fr/ird/observe/validation/ValidatorsMap.java | 121 - .../fr.ird.observe.business.db.DataSourceProvider | 2 - .../fr.ird.observe.report.model.ReportOperation | 6 - .../src/main/resources/faunaminmax.csv | 164 -- .../i18n/observe-business_en_GB.properties | 234 -- .../i18n/observe-business_es_ES.properties | 234 -- .../i18n/observe-business_fr_FR.properties | 234 -- .../src/main/resources/observe-ehcache.xml | 49 - observe-business/src/main/resources/xwork.xml | 30 - .../java/fr/ird/converter/FloatConverterTest.java | 78 - .../java/fr/ird/observe/EntityDetectorTest.java | 336 --- .../test/java/fr/ird/observe/db/DBTestHelper.java | 604 ----- .../java/fr/ird/observe/db/DataServiceTest.java | 338 --- .../fr/ird/observe/db/DataSourceFactoryTest.java | 84 - .../fr/ird/observe/db/ReplicationServiceTest.java | 297 --- .../observe/db/impl/H2DataSourceConfigTest.java | 249 -- .../observe/db/impl/PGDataSourceConfigTest.java | 300 --- .../java/fr/ird/observe/gps/GPSFileReaderTest.java | 187 -- .../test/java/fr/ird/observe/gps/GPSRouteTest.java | 162 -- .../java/fr/ird/observe/gps/GPSServiceTest.java | 94 - .../fr/ird/observe/its/DataSourceFactoryIT.java | 323 --- .../test/java/fr/ird/observe/its/PGInstallIT.java | 172 -- .../java/fr/ird/observe/its/RestoreEmptyPGIT.java | 81 - .../migration/AbstractDataSourceMigrationTest.java | 67 - .../its/migration/AbstractMigrationTest.java | 139 -- .../its/migration/H2DataSourceMigrationIT.java | 390 --- .../its/migration/PGDataSourceMigrationIT.java | 140 -- .../h2ToLast/AbstractH2MigrationToLastIT.java | 114 - .../its/migration/h2ToLast/MigrationV4_0IT.java | 48 - .../its/replication/AbstractReplicateDataTest.java | 417 ---- .../AbstractReplicateReferentielTest.java | 269 -- .../its/replication/AbstractReplicateTest.java | 88 - .../observe/its/replication/H2ReplicateDataIT.java | 69 - .../its/replication/H2ReplicateDataTest.java | 370 --- .../its/replication/H2ReplicateReferentielIT.java | 60 - .../observe/its/replication/PGReplicateDataIT.java | 75 - .../its/replication/PGReplicateReferentielIT.java | 57 - .../its/replication/ReplicationDataModel.java | 170 -- .../ird/observe/its/report/AbstractReportIT.java | 290 --- .../its/report/accessoryCatch/Report2IT.java | 51 - .../its/report/accessoryCatch/ReportIT.java | 105 - .../report/accessoryCatchByGroup/Report2IT.java | 51 - .../its/report/accessoryCatchByGroup/ReportIT.java | 154 -- .../its/report/activityWithComment/ReportIT.java | 81 - .../observe/its/report/allActivitys/ReportIT.java | 79 - .../its/report/dailySetAndCatch/ReportIT.java | 96 - .../ird/observe/its/report/dcpUsage/ReportIT.java | 135 - .../its/report/setByAssociation/Report2IT.java | 52 - .../its/report/setByAssociation/ReportIT.java | 124 - .../report/targetCatchByAssociation/ReportIT.java | 94 - .../targetDiscardedByAssociation/ReportIT.java | 94 - .../observe/validation/ValidationServiceTest.java | 517 ---- .../src/test/resources/db/4.0.2/referentiel.sql.gz | Bin 138257 -> 0 bytes .../referentiel/Ocean-test3-error-validation.xml | 32 - .../referentiel/Program-test1-error-validation.xml | 32 - .../referentiel/Program-test3-info-validation.xml | 32 - .../seine/TripSeine-test2-error-validation.xml | 31 - .../seine/TripSeine-test3-warning-validation.xml | 31 - .../resources/fr/ird/observe/gps/GL50_13_small.gpx | 167 -- .../ird/observe/gps/testInterval_allAccepted.gpx | 157 -- .../ird/observe/gps/testInterval_allRejected.gpx | 157 -- .../gps/testInterval_firtPointsRejected.gpx | 157 -- .../gps/testInterval_insidePointsRejected.gpx | 157 -- .../gps/testInterval_insidePointsRejected2.gpx | 157 -- .../gps/testInterval_lastPointsRejected.gpx | 157 -- .../src/test/resources/log4j.properties | 33 - .../resources/reports/accessoryCatchByGroup.sql.gz | Bin 107164 -> 0 bytes .../resources/reports/activityWithComment.sql.gz | Bin 106335 -> 0 bytes .../src/test/resources/reports/allActivitys.sql.gz | Bin 106335 -> 0 bytes .../test/resources/reports/dailySetAndCatch.sql.gz | Bin 108462 -> 0 bytes .../src/test/resources/reports/dcpUsage.sql.gz | Bin 106816 -> 0 bytes .../test/resources/reports/setByAssociation.sql.gz | Bin 107630 -> 0 bytes .../resources/reports/setByAssociation2.sql.gz | Bin 109225 -> 0 bytes .../reports/targetCatchByAssociation.sql.gz | Bin 108732 -> 0 bytes .../reports/targetDiscardedByAssociation.sql.gz | Bin 108725 -> 0 bytes 158 files changed, 29550 deletions(-) diff --git a/observe-business/LICENSE.txt b/observe-business/LICENSE.txt deleted file mode 100644 index 94a9ed0..0000000 --- a/observe-business/LICENSE.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - <one line to give the program's name and a brief idea of what it does.> - Copyright (C) <year> <name of author> - - 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/>. - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - <program> Copyright (C) <year> <name of author> - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -<http://www.gnu.org/licenses/>. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/observe-business/README.md b/observe-business/README.md deleted file mode 100644 index d2e50d3..0000000 --- a/observe-business/README.md +++ /dev/null @@ -1,2 +0,0 @@ -To deploy new version of pom: mvn deploy -To install localy: mvn install diff --git a/observe-business/changelog.txt b/observe-business/changelog.txt deleted file mode 100644 index 60d39cb..0000000 --- a/observe-business/changelog.txt +++ /dev/null @@ -1,2 +0,0 @@ -0.1 chemit 200812?? - - first release \ No newline at end of file diff --git a/observe-business/pom.xml b/observe-business/pom.xml deleted file mode 100644 index b5a788b..0000000 --- a/observe-business/pom.xml +++ /dev/null @@ -1,413 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - #%L - ObServe :: Business - - $HeadURL$ - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser 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 Lesser Public License for more details. - - You should have received a copy of the GNU General Lesser Public - License along with this program. If not, see - <http://www.gnu.org/licenses/lgpl-3.0.html>. - #L% - --> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>fr.ird.observe</groupId> - <artifactId>observe</artifactId> - <version>4.0.2-SNAPSHOT</version> - </parent> - - <artifactId>observe-business</artifactId> - - <name>ObServe :: Business</name> - <description>ObServe business module</description> - - <dependencies> - - <!-- sibling dependencies --> - <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>observe-entities</artifactId> - <version>${project.version}</version> - </dependency> - - <!-- Nuiton --> - <dependency> - <groupId>org.nuiton</groupId> - <artifactId>nuiton-utils</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton</groupId> - <artifactId>nuiton-validator</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton</groupId> - <artifactId>nuiton-config</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton</groupId> - <artifactId>nuiton-decorator</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton.i18n</groupId> - <artifactId>nuiton-i18n</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton</groupId> - <artifactId>nuiton-converter</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton</groupId> - <artifactId>nuiton-csv</artifactId> - </dependency> - - <!-- comons --> - <dependency> - <groupId> org.apache.commons</groupId> - <artifactId>commons-lang3</artifactId> - </dependency> - <dependency> - <groupId> org.apache.commons</groupId> - <artifactId>commons-collections4</artifactId> - </dependency> - <dependency> - <groupId>commons-logging</groupId> - <artifactId>commons-logging</artifactId> - </dependency> - <dependency> - <groupId>commons-collections</groupId> - <artifactId>commons-collections</artifactId> - </dependency> - <dependency> - <groupId>commons-io</groupId> - <artifactId>commons-io</artifactId> - </dependency> - <dependency> - <groupId>commons-beanutils</groupId> - <artifactId>commons-beanutils</artifactId> - </dependency> - <dependency> - <groupId>commons-jxpath</groupId> - <artifactId>commons-jxpath</artifactId> - </dependency> - <dependency> - <groupId>com.google.guava</groupId> - <artifactId>guava</artifactId> - </dependency> - - <!-- ToPIA --> - - <dependency> - <groupId>org.nuiton.topia</groupId> - <artifactId>topia-persistence</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton.topia</groupId> - <artifactId>topia-service-replication</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton.topia</groupId> - <artifactId>topia-service-migration</artifactId> - </dependency> - - <dependency> - <groupId>xpp3</groupId> - <artifactId>xpp3</artifactId> - </dependency> - - <!-- JAXX --> - <dependency> - <groupId>org.nuiton.jaxx</groupId> - <artifactId>jaxx-runtime</artifactId> - <exclusions> - <exclusion> - <groupId>javax.help</groupId> - <artifactId>javahelp</artifactId> - </exclusion> - <exclusion> - <groupId>org.swinglabs</groupId> - <artifactId>swingx</artifactId> - </exclusion> - </exclusions> - </dependency> - <dependency> - <groupId>org.nuiton.jaxx</groupId> - <artifactId>jaxx-validator</artifactId> - <exclusions> - <exclusion> - <groupId>javax.help</groupId> - <artifactId>javahelp</artifactId> - </exclusion> - <exclusion> - <groupId>org.swinglabs</groupId> - <artifactId>swingx</artifactId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>org.swinglabs.swingx</groupId> - <artifactId>swingx-common</artifactId> - </dependency> - - <!-- xworks (validation) --> - <dependency> - <groupId>org.apache.struts.xwork</groupId> - <artifactId>xwork-core</artifactId> - </dependency> - - <!-- persistence --> - - <dependency> - <groupId>com.h2database</groupId> - <artifactId>h2</artifactId> - </dependency> - <dependency> - <groupId>postgresql</groupId> - <artifactId>postgresql</artifactId> - </dependency> - <dependency> - <groupId>org.hibernate</groupId> - <artifactId>hibernate-core</artifactId> - </dependency> - - <!-- hibernate jmx support --> - - <!--dependency> - <groupId>org.hibernate</groupId> - <artifactId>hibernate-jmx</artifactId> - </dependency--> - - <!-- test --> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - </dependency> - <dependency> - <groupId>org.nuiton.topia</groupId> - <artifactId>topia-persistence</artifactId> - <classifier>tests</classifier> - </dependency> - <dependency> - <groupId>org.nuiton.topia</groupId> - <artifactId>topia-service-replication</artifactId> - <scope>test</scope> - <classifier>tests</classifier> - </dependency> - <dependency> - <groupId>org.nuiton</groupId> - <artifactId>nuiton-validator</artifactId> - <classifier>tests</classifier> - </dependency> - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-jcl</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <scope>test</scope> - </dependency> - - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - <includes> - <include>**/*</include> - </includes> - </resource> - <resource> - <directory>src/main/filters</directory> - <filtering>true</filtering> - <includes> - <include>*.properties</include> - </includes> - </resource> - </resources> - <testResources> - <testResource> - <directory>src/test/resources</directory> - <includes> - <include>**/*</include> - </includes> - </testResource> - </testResources> - <plugins> - - <plugin> - <groupId>org.nuiton.i18n</groupId> - <artifactId>i18n-maven-plugin</artifactId> - <executions> - <execution> - <goals> - <goal>parserJava</goal> - <goal>gen</goal> - </goals> - </execution> - </executions> - </plugin> - - <plugin> - <artifactId>maven-jar-plugin</artifactId> - <executions> - <execution> - <id>attach-test</id> - <goals> - <goal>test-jar</goal> - </goals> - </execution> - </executions> - </plugin> - - </plugins> - </build> - - <profiles> - - <profile> - <id>run-report-its</id> - <build> - <defaultGoal>integration-test</defaultGoal> - <plugins> - <plugin> - <artifactId>maven-surefire-plugin</artifactId> - <executions> - <execution> - <id>integration-report-tests</id> - <phase>integration-test</phase> - <goals> - <goal>test</goal> - </goals> - <configuration> - <includes> - <include>**/report/**/*IT.java</include> - </includes> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - </profile> - - <profile> - <id>run-replication-its</id> - <build> - <defaultGoal>integration-test</defaultGoal> - <plugins> - <plugin> - <artifactId>maven-surefire-plugin</artifactId> - <executions> - <execution> - <id>integration-report-tests</id> - <phase>integration-test</phase> - <goals> - <goal>test</goal> - </goals> - <configuration> - <includes> - <include>**/replication/*IT.java</include> - </includes> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - </profile> - - <profile> - <id>run-migration-its</id> - <build> - <defaultGoal>integration-test</defaultGoal> - <plugins> - <plugin> - <artifactId>maven-surefire-plugin</artifactId> - <executions> - <execution> - <id>integration-report-tests</id> - <phase>integration-test</phase> - <goals> - <goal>test</goal> - </goals> - <configuration> - <includes> - <include>**/migration/**/*IT.java</include> - </includes> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - </profile> - - <profile> - <id>run-its</id> - <activation> - <property> - <name>performRelease</name> - <value>true</value> - </property> - </activation> - <build> - <defaultGoal>integration-test</defaultGoal> - <plugins> - <plugin> - <artifactId>maven-surefire-plugin</artifactId> - <executions> - <execution> - <id>integration-tests</id> - <phase>integration-test</phase> - <goals> - <goal>test</goal> - </goals> - <configuration> - <includes> - <include>**/*IT.java</include> - </includes> - <excludes> - <exclude>**/RestoreEmptyPGIT.java</exclude> - <exclude>**/report/**/*IT.java</exclude> - </excludes> - </configuration> - </execution> - - <execution> - <id>after-integration-tests</id> - <phase>post-integration-test</phase> - <goals> - <goal>test</goal> - </goals> - <configuration> - <includes> - <include>**/RestoreEmptyPGIT.java</include> - </includes> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - </profile> - - </profiles> -</project> diff --git a/observe-business/src/license/THIRD-PARTY.properties b/observe-business/src/license/THIRD-PARTY.properties deleted file mode 100644 index 5a2ad0e..0000000 --- a/observe-business/src/license/THIRD-PARTY.properties +++ /dev/null @@ -1,30 +0,0 @@ -# Generated by org.codehaus.mojo.license.AddThirdPartyMojo -#------------------------------------------------------------------------------- -# Already used licenses in project : -# - Apache License 2.0 -# - Apache Software License, version 1.1 -# - BSD License -# - COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 -# - Common Public License Version 1.0 -# - GNU Lesser General Public License, version 2.1 -# - GNU Library or Lesser General Public License -# - General Public License (GPL) -# - Indiana University Extreme! Lab Software License, vesion 1.1.1 -# - Lesser General Public License (LGPL) -# - Lesser General Public License (LGPL) v 3.0 -# - Lesser General Public License (LPGL) -# - Lesser General Public License (LPGL) v 2.1 -# - MIT License -# - MPL 1.1 -# - New BSD License -# - Public Domain -# - The Apache Software License, Version 2.0 -# - The H2 License, Version 1.0 -# - license.txt -#------------------------------------------------------------------------------- -# Please fill the missing licenses for dependencies : -# -# -#Thu Jun 27 15:55:14 CEST 2013 -commons-primitives--commons-primitives--1.0=The Apache Software License, Version 2.0 -dom4j--dom4j--1.6.1=BSD License diff --git a/observe-business/src/main/filters/observe-reports.properties b/observe-business/src/main/filters/observe-reports.properties deleted file mode 100644 index 512bcf2..0000000 --- a/observe-business/src/main/filters/observe-reports.properties +++ /dev/null @@ -1,854 +0,0 @@ -### -# #%L -# ObServe :: Business -# %% -# Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit -# %% -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/gpl-3.0.html>. -# #L% -### - -################################################################################ -## Liste des activit\u00e9s avec des comments -################################################################################ - -report.activityWithComment.name=Activit\u00e9s avec comment et leurs positions -report.activityWithComment.description=Afficher les activit\u00e9s avec comment et leurs positions g\u00e9ographiques -report.activityWithComment.columns=Jour - Heure observation, Latitude, Longitude, Activit\u00e9, Commentaire -report.activityWithComment.request.1=0,0|row|\ - Select concat(day(r.date), '/', month(r.date), '/', year(r.date), ' ', hour(a.time), ':', minute(a.time)), a.latitude, a.longitude, ab.label2, a.comment \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.vesselActivitySeine ab \ - Where \ - m.id = :tripId \ - and a.comment is not null \ - Order By r.date, a.time - -################################################################################ -## Liste de toutes les activit\u00e9s et leurs positions -################################################################################ - -report.allActivitys.name=Toutes les activit\u00e9s et leurs positions -report.allActivitys.description=Afficher toutes les activit\u00e9s et leurs positions g\u00e9ographiques -report.allActivitys.columns=Jour - Heure observation, Latitude, Longitude, Activit\u00e9, Commentaire -report.allActivitys.request.1=0,0|row|\ - Select concat(day(r.date), '/', month(r.date), '/', year(r.date), ' ', hour(a.time), ':', minute(a.time)), a.latitude, a.longitude, ab.label2, a.comment \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.vesselActivitySeine ab \ - Where \ - m.id = :tripId \ - Order By r.date, a.time - -################################################################################ -## Nombre de cal\u00e9es et captures journali\u00e8res d'une mar\u00e9e -################################################################################ - -report.dailySetAndCatch.name=Nombre de cal\u00e9es et captures journali\u00e8res d'une mar\u00e9e -report.dailySetAndCatch.description=Afficher le nombre de cal\u00e9es et les captures journali\u00e8res d\u2019une cal\u00e9e -report.dailySetAndCatch.columns=Jour observation,Nombre de cal\u00e9es ,Captures thon -report.dailySetAndCatch.request.1=0,0|row|\ - Select concat(day(r.date), '/', month(r.date), '/', year(r.date)), Count(distinct a), Sum(ct.catchWeight) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine s \ - left join s.targetCatch as ct \ - Where \ - m.id = :tripId \ - Group By r.date \ - Order By r.date - -################################################################################ -## Utilisation des DCP -################################################################################ - -report.dcpUsage.name=Utilisation des DCP -report.dcpUsage.description=Tableau r\u00e9capitulatif du nombre de DCP visit\u00e9s selon l\u2019action effectu\u00e9e (visites avec et sans p\u00eache, mis \u00e0 l\u2019eau, r\u00e9cuperation), et tortues observ\u00e9es -report.dcpUsage.columns=Type de DCP (Tableau 8),Nombre visit\u00e9s,Nombre p\u00each\u00e9s,Nombre mis \u00e0 l\u2019eau seuls,Nombre renforc\u00e9s par radeau balis\u00e9,R\u00e9cup\u00e9r\u00e9 sans p\u00eache,Nombre de tortues associ\u00e9es -report.dcpUsage.repeatVariable.typeObjetId=java.lang.String|\ - Select to.id \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.floatingObject dcp \ - Join dcp.objectType to \ - Where \ - m.id = :tripId \ - Order by to.code - -report.dcpUsage.request.1=0,0|row|\ - Select concat(str(to.code) , ' - ', to.label2) \ - From ObjectTypeImpl to \ - Where \ - to.id = :typeObjetId -report.dcpUsage.request.1.repeat=typeObjetId|column - -report.dcpUsage.request.2=1,0|row|\ - Select Count(dcp) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.floatingObject dcp \ - Where \ - m.id = :tripId \ - and dcp.objectType.id = :typeObjetId \ - and dcp.objectOperation.id = 'fr.ird.observe.entities.referentiel.seine.ObjectOperation#1239832686249#0.8268884472438458' -report.dcpUsage.request.2.repeat=typeObjetId|column - -report.dcpUsage.request.3=2,0|row|\ - Select Count(dcp) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.floatingObject dcp \ - Where \ - m.id = :tripId \ - and dcp.objectType.id = :typeObjetId \ - and dcp.objectOperation.id = 'fr.ird.observe.entities.referentiel.seine.ObjectOperation#1239832686249#0.8431519556575698' -report.dcpUsage.request.3.repeat=typeObjetId|column - -report.dcpUsage.request.4=3,0|row|\ - Select Count(dcp) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.floatingObject dcp \ - Where \ - m.id = :tripId \ - and dcp.objectType.id = :typeObjetId \ - and dcp.objectOperation.id = 'fr.ird.observe.entities.referentiel.seine.ObjectOperation#1239832686248#0.8669327599318251' -report.dcpUsage.request.4.repeat=typeObjetId|column - -report.dcpUsage.request.5=4,0|row|\ - Select Count(dcp) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.floatingObject dcp \ - Where \ - m.id = :tripId \ - and dcp.objectType.id = :typeObjetId \ - and dcp.objectFate.id = 'fr.ird.observe.entities.referentiel.seine.ObjectFate#1396860761530#0.8869464242156488' \ - and dcp.objectOperation.id != 'fr.ird.observe.entities.referentiel.seine.ObjectOperation#1239832686248#0.8669327599318251' -report.dcpUsage.request.5.repeat=typeObjetId|column - -report.dcpUsage.request.6=5,0|row|\ - Select Count(dcp) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.floatingObject dcp \ - Where \ - m.id = :tripId \ - and dcp.objectType.id = :typeObjetId \ - and dcp.objectOperation.code = 'fr.ird.observe.entities.referentiel.seine.ObjectOperation#1239832686249#0.7838704130950722' -report.dcpUsage.request.6.repeat=typeObjetId|column - -report.dcpUsage.request.7=6,0|row| \ - Select Sum(efo.count) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.floatingObject dcp \ - Join dcp.objectObservedSpecies efo \ - Where \ - m.id = :tripId \ - and dcp.objectType.id = :typeObjetId \ - and efo.species.speciesGroup.id = 'fr.ird.observe.entities.referentiel.SpeciesGroup#1239832683690#0.24333033683679461' -report.dcpUsage.request.7.repeat=typeObjetId|column - -################################################################################ -## Nombre des cal\u00e9es selon le type d'association -################################################################################ - -report.setByAssociation.name=Nombre de cal\u00e9es selon le type d\u2019association -report.setByAssociation.description=Afficher la r\u00e9partitions des cal\u00e9es selon le type d\u2019association l\u2019issue du coup. Les coups sur BL baleine et BO requin-baleine sont sp\u00e9cifi\u00e9s. -report.setByAssociation.columns=BL sans baleine, BL avec baleine, BO avec requin-baleine, BO sans requin-baleine, Total -report.setByAssociation.rows=Coups positifs, Coups nuls, Total -report.setByAssociation.operations.1=SumIntRow -report.setByAssociation.operations.2=SumIntColumn -report.setByAssociation.request.1=0,0|column|\ - Select Count(a) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and a.setSeine.schoolType = 2 \ - and a.setSeine.reasonForNullSet is null \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9395222812356602' \ - and os not in elements(a.observedSystem) - -report.setByAssociation.request.2=0,1|column|\ - Select Count(a) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and a.setSeine.schoolType = 2 \ - and a.setSeine.reasonForNullSet is not null \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9395222812356602' \ - and os not in elements(a.observedSystem) - -report.setByAssociation.request.3=1,0|column|\ - Select Count(a) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and a.setSeine.schoolType = 2 \ - and a.setSeine.reasonForNullSet is null \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9395222812356602' \ - and os in elements(a.observedSystem) - -report.setByAssociation.request.4=1,1|column|\ - Select Count(a) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and a.setSeine.schoolType = 2 \ - and a.setSeine.reasonForNullSet is not null \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9395222812356602' \ - and os in elements(a.observedSystem) - -report.setByAssociation.request.5=2,0|column|\ - Select Count(a) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and a.setSeine.schoolType = 1 \ - and a.setSeine.reasonForNullSet is null \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9217864901728908' \ - and os in elements(a.observedSystem) - -report.setByAssociation.request.6=2,1|column|\ - Select Count(a) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and a.setSeine.schoolType = 1 \ - and a.setSeine.reasonForNullSet is not null \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9217864901728908' \ - and os in elements(a.observedSystem) - -report.setByAssociation.request.7=3,0|column|\ - Select Count(a) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and a.setSeine.schoolType = 1 \ - and a.setSeine.reasonForNullSet is null \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9217864901728908' \ - and os not in elements(a.observedSystem) - -report.setByAssociation.request.8=3,1|column|\ - Select Count(a) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and a.setSeine.schoolType = 1 \ - and a.setSeine.reasonForNullSet is not null \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9217864901728908' \ - and os not in elements(a.observedSystem) - -################################################################################ -## Captures thon par type d'association -################################################################################ - -report.targetCatchByAssociation.name=Capture de thon selon le type d'association (en t) -report.targetCatchByAssociation.description=Afficher la r\u00e9partitions des captures de thons selon le type d'association -report.targetCatchByAssociation.columns=YFT, SKJ, BET, LTA, FRI, Autres, Total -report.targetCatchByAssociation.rows=BL sans baleine, BL avec baleine, BO avec requin-baleine, BO sans requin-baleine, Total -report.targetCatchByAssociation.operations.1=SumRow -report.targetCatchByAssociation.operations.2=SumColumn - -# ligne 1 -report.targetCatchByAssociation.request.1=0,0|row|\ - Select \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then 0.0 \ - Else ct.catchWeight End) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 2 \ - Join c.targetCatch ct \ - with ct.discarded = false, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9395222812356602' \ - and os not in elements(a.observedSystem) - -# ligne 2 -report.targetCatchByAssociation.request.7=0,1|row|\ - Select \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then 0.0 \ - Else ct.catchWeight End) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 2 \ - Join c.targetCatch ct \ - with ct.discarded = false, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9395222812356602' \ - and os in elements(a.observedSystem) - -# ligne 3 -report.targetCatchByAssociation.request.13=0,2|row|\ - Select \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then 0.0 \ - Else ct.catchWeight End) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 1 \ - Join c.targetCatch ct \ - with ct.discarded = false, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9217864901728908' \ - and os in elements(a.observedSystem) - -# ligne 4 -report.targetCatchByAssociation.request.19=0,3|row|\ - Select \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then 0.0 \ - Else ct.catchWeight End) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 1 \ - Join c.targetCatch ct \ - with ct.discarded = false, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9217864901728908' \ - and os not in elements(a.observedSystem) - -################################################################################ -## Rejets thons selon le type d'association -################################################################################ - -report.targetDiscardedByAssociation.name=Rejets de thons selon le type d\u2019association (en t) -report.targetDiscardedByAssociation.description=Afficher la r\u00e9partitions des rejets de thons selon le type d'association -report.targetDiscardedByAssociation.columns=YFT, SKJ, BET, LTA, FRI, Autres, Total -report.targetDiscardedByAssociation.rows=BL sans baleine, BL avec baleine, BO avec requin-baleine, BO sans requin-baleine, Total -report.targetDiscardedByAssociation.operations.1=SumRow -report.targetDiscardedByAssociation.operations.2=SumColumn - -# ligne 1 -report.targetDiscardedByAssociation.request.1=0,0|row|\ - Select \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then 0.0 \ - Else ct.catchWeight End) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 2 \ - Join c.targetCatch ct \ - with ct.discarded = true, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9395222812356602' \ - and os not in elements(a.observedSystem) - -# ligne 2 -report.targetDiscardedByAssociation.request.7=0,1|row|\ - Select \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then 0.0 \ - Else ct.catchWeight End) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 2 \ - Join c.targetCatch ct \ - with ct.discarded = true, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9395222812356602' \ - and os in elements(a.observedSystem) - -# ligne 3 -report.targetDiscardedByAssociation.request.13=0,2|row|\ - Select \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then 0.0 \ - Else ct.catchWeight End) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 1 \ - Join c.targetCatch ct \ - with ct.discarded = true, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9217864901728908' \ - and os in elements(a.observedSystem) - -# ligne 4 -report.targetDiscardedByAssociation.request.19=0,3|row|\ - Select \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then ct.catchWeight \ - Else 0.0 End), \ - Sum(CASE ct.weightCategory.species.topiaId When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.8943253454598569' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685474#0.975344121171992' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685475#0.13349466123905152' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.8024257002747615' Then 0.0 \ - When 'fr.ird.observe.entities.referentiel.Species#1239832685477#0.3846921632590058' Then 0.0 \ - Else ct.catchWeight End) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 1 \ - Join c.targetCatch ct \ - with ct.discarded = true, \ - ObservedSystemImpl os \ - Where \ - m.id = :tripId \ - and os.topiaId = 'fr.ird.observe.entities.referentiel.seine.ObservedSystem#1239832686428#0.9217864901728908' \ - and os not in elements(a.observedSystem) - -################################################################################ -## Captures accessoires observ\u00e9es -################################################################################ - - -report.accessoryCatch.name=Liste des captures accessoires selon le type de banc, filtr\u00e9es par groupe -report.accessoryCatch.description=Afficher les captures accessoires par groupe d'esp\u00e8ce\nLes poids sont exprim\u00e9s en tonnes. -report.accessoryCatch.columns=Esp\u00e8ce, Banc libre, Banc objet -report.accessoryCatch.variable.speciesGroupId=fr.ird.observe.entities.referentiel.SpeciesGroup|From SpeciesGroupImpl ge Order By ge.code -report.accessoryCatch.repeatVariable.speciesId=java.lang.String|\ - Select e.id From SpeciesImpl e \ - Where e.speciesGroup.id = :speciesGroupId \ - Order By e.homeId - -report.accessoryCatch.request.1=0,0|row|\ - Select \ - concat('[FAO]', (case when e.faoCode is not null then e.faoCode else '-' end), \ - ' [sc]', (case when e.scientificLabel is not null then e.scientificLabel else '-' end), \ - ' [fr]', (case when e.label2 is not null then e.label2 else '-' end)) \ - From SpeciesImpl e \ - Where e.id = :speciesId -report.accessoryCatch.request.1.repeat=speciesId|column - -report.accessoryCatch.request.2=1,0|row|\ - Select \ - case when Count(ca) > 0 then \ - concat('+', \ - case when Sum(ca.totalCount) is not null then concat(' Effectif : ', str(Sum(ca.totalCount))) else '' end , \ - case when Sum(ca.catchWeight) is not null then concat(' Poids total (t) : ' , str(Sum(ca.catchWeight))) else '' end ) \ - else '-' end \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 2 \ - Join c.nonTargetCatch ca \ - with ca.species.id = :speciesId \ - Where m.id = :tripId -report.accessoryCatch.request.2.repeat=speciesId|column - -report.accessoryCatch.request.3=2,0|row|\ - Select \ - case when Count(ca) > 0 then \ - concat('+', \ - case when Sum(ca.totalCount) is not null then concat(' Effectif : ', str(Sum(ca.totalCount))) else '' end , \ - case when Sum(ca.catchWeight) is not null then concat(' Poids total (t) : ' , str(Sum(ca.catchWeight))) else '' end ) \ - else '-' end \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - with c.schoolType = 1 \ - Join c.nonTargetCatch ca \ - with ca.species.id = :speciesId \ - Where m.id = :tripId -report.accessoryCatch.request.3.repeat=speciesId|column - -################################################################################ -## Captures accessoires par speciesGroup d'esp\u00e8ces -################################################################################ - -report.accessoryCatchByGroup.name=D\u00e9nombrement des captures accessoires et devenir, filtr\u00e9s par groupe -report.accessoryCatchByGroup.description=Afficher les nombres de captures accessoires par groupe d'esp\u00e8ce selon le type de banc et le devenir -report.accessoryCatchByGroup.columns=Esp\u00e8ce, Total BL, Total BO, Sorti vivant/\u00e9chapp\u00e9, Sorti mort, Rejet\u00e9 vivant, Rejet\u00e9 mort, Partiellement conserv\u00e9, Cuve, Cuisine, Autre -report.accessoryCatchByGroup.variable.speciesGroupId=fr.ird.observe.entities.referentiel.SpeciesGroup|From SpeciesGroupImpl ge Order By ge.code - -report.accessoryCatchByGroup.request.1=0,0|row|\ - Select \ - concat(\ - '[FAO]', (case when e.faoCode is not null then e.faoCode else '-' end), \ - ' [sc]', (case when e.scientificLabel is not null then e.scientificLabel else '-' end), \ - ' [fr]', (case when e.label2 is not null then e.label2 else '-' end)), \ - Sum(case c.schoolType when 2 then ca.totalCount else 0.0 end), \ - Sum(case c.schoolType when 1 then ca.totalCount else 0.0 end), \ - Sum(case ca.speciesFate.id when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.9931091059863436' then ca.totalCount \ - when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683618#0.06155887805368032' then ca.totalCount \ - else 0.0 end), \ - Sum(case ca.speciesFate.id when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.11883784875534997' then ca.totalCount \ - else 0.0 end), \ - Sum(case ca.speciesFate.id when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.5308862132841506' then ca.totalCount \ - else 0.0 end), \ - Sum(case ca.speciesFate.id when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.6250731662108877' then ca.totalCount \ - else 0.0 end), \ - Sum(case ca.speciesFate.id when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683620#0.46609703818634485' then ca.totalCount \ - else 0.0 end), \ - Sum(case ca.speciesFate.id when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.5722739932065866' then ca.totalCount \ - else 0.0 end), \ - Sum(case ca.speciesFate.id when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683621#0.6728026426066158' then ca.totalCount \ - else 0.0 end), \ - Sum(case ca.speciesFate.id when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.9931091059863436' then 0.0 \ - when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683618#0.06155887805368032' then 0.0 \ - when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.11883784875534997' then 0.0 \ - when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.5308862132841506' then 0.0 \ - when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.6250731662108877' then 0.0 \ - when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683620#0.46609703818634485' then 0.0 \ - when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683619#0.5722739932065866' then 0.0 \ - when 'fr.ird.observe.entities.referentiel.seine.SpeciesFate#1239832683621#0.6728026426066158' then 0.0 \ - else ca.totalCount end) \ - From TripSeineImpl m \ - Join m.route r \ - Join r.activitySeine a \ - Join a.setSeine c \ - Join c.nonTargetCatch ca \ - Join ca.species e \ - with e.speciesGroup.id = :speciesGroupId \ - Where m.id = :tripId \ - Group by e \ - Order By e.homeId - -########################################################### -## Distribution des tailles par espèces non ciblées -########################################################### - -report.nonTargetDistributionLengths.name=Distribution des tailles par esp\u00e8ces non cibl\u00e9es -report.nonTargetDistributionLengths.description=Afficher la nombre d'individus mesur\u00e9s par classe de taille pour les esp\u00e8ces non cibl\u00e9es -report.nonTargetDistributionLengths.columns=Classe de taille,Effectif -report.nonTargetDistributionLengths.operations.1=GroupByLength -report.nonTargetDistributionLengths.variable.speciesId=fr.ird.observe.entities.referentiel.Species|\ -Select distinct ntl.species \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.nonTargetSample nts \ -Join nts.nonTargetLength ntl \ -Where t.id = :tripId -report.nonTargetDistributionLengths.request.1=0,0|row| \ -Select ntl.length, sum(ntl.count) \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.nonTargetSample nts \ -Join nts.nonTargetLength ntl \ -Where t.id = :tripId \ -And ntl.species.id = :speciesId \ -Group By ntl.length \ -Order By ntl.length - -#################################################################### -## Distribution des tailles des conservés par espèces ciblées (LD1) -#################################################################### - -report.targetStoredDistributionLengthsLD1.name=Distribution des tailles des captures par esp\u00e8ces cibl\u00e9es (mesure LD1) -report.targetStoredDistributionLengthsLD1.description=Afficher le nombre d'individus captur\u00e9s, mesur\u00e9s par classe de taille LD1 pour les esp\u00e8ces cibl\u00e9es -report.targetStoredDistributionLengthsLD1.columns=Classe de taille,Effectif -report.targetStoredDistributionLengthsLD1.operations.1=GroupByLength -report.targetStoredDistributionLengthsLD1.variable.speciesId=fr.ird.observe.entities.referentiel.Species|\ -Select distinct tl.species \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetSample ts \ -Join ts.targetLength tl \ -Where t.id = :tripId \ -And tl.measureType = 1 \ -And ts.discarded = false -report.targetStoredDistributionLengthsLD1.request.1=0,0|row| \ -Select tl.length , Sum(tl.count) \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetSample ts \ -Join ts.targetLength tl \ -Where t.id = :tripId \ - And tl.species.id = :speciesId \ - And tl.measureType = 1 \ - And ts.discarded = false \ -Group By tl.length \ -Order By tl.length - -################################################################ -## Distribution des tailles des rejets par espèces ciblées (LD1) -################################################################ - -report.targetDiscardedDistributionLengthsLD1.name=Distribution des tailles des rejets par esp\u00e8ces cibl\u00e9es (mesure LD1) -report.targetDiscardedDistributionLengthsLD1.description=Afficher la nombre d'individus rejet\u00e9s, mesur\u00e9s par classe de taille LD1 pour les esp\u00e8ces cibl\u00e9es -report.targetDiscardedDistributionLengthsLD1.columns=Classe de taille,Effectif -report.targetDiscardedDistributionLengthsLD1.operations.1=GroupByLength -report.targetDiscardedDistributionLengthsLD1.variable.speciesId=fr.ird.observe.entities.referentiel.Species|\ -Select distinct tl.species \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetSample ts \ -Join ts.targetLength tl \ -Where t.id = :tripId \ -And tl.measureType = 1 \ -And ts.discarded = true -report.targetDiscardedDistributionLengthsLD1.request.1=0,0|row| \ -Select tl.length , Sum(tl.count) \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetSample ts \ -Join ts.targetLength tl \ -Where t.id = :tripId \ - And tl.species.id = :speciesId \ - And tl.measureType = 1\ - And ts.discarded = true \ -Group By tl.length \ -Order By tl.length - -############################################################### -## Distribution des tailles des conservés par espèces ciblées (LF) -############################################################### - -report.targetStoredDistributionLengthsLF.name=Distribution des tailles des captures par esp\u00e8ces cibl\u00e9es (mesure LF) -report.targetStoredDistributionLengthsLF.description=Afficher le nombre d'individus captur\u00e9s, mesur\u00e9s par classe de taille LF pour les esp\u00e8ces cibl\u00e9es -report.targetStoredDistributionLengthsLF.columns=Classe de taille,Effectif -report.targetStoredDistributionLengthsLF.operations.1=GroupByLength -report.targetStoredDistributionLengthsLF.variable.speciesId=fr.ird.observe.entities.referentiel.Species|\ -Select distinct tl.species \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetSample ts \ -Join ts.targetLength tl \ -Where t.id = :tripId \ -And tl.measureType = 2 \ -And ts.discarded = false -report.targetStoredDistributionLengthsLF.request.1=0,0|row| \ -Select tl.length , Sum(tl.count) \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetSample ts \ -Join ts.targetLength tl \ -Where t.id = :tripId \ - And tl.species.id = :speciesId \ - And tl.measureType = 2 \ - And ts.discarded = false \ -Group By tl.length \ -Order By tl.length - -############################################################### -## Distribution des tailles des rejets par espèces ciblées (LF) -############################################################### - -report.targetDiscardedDistributionLengthsLF.name=Distribution des tailles des rejets par esp\u00e8ces cibl\u00e9es (mesure LF) -report.targetDiscardedDistributionLengthsLF.description=Afficher le nombre d'individus rejet\u00e9s, mesur\u00e9s par classe de taille LF pour les esp\u00e8ces cibl\u00e9es -report.targetDiscardedDistributionLengthsLF.columns=Classe de taille,Effectif -report.targetDiscardedDistributionLengthsLF.operations.1=GroupByLength -report.targetDiscardedDistributionLengthsLF.variable.speciesId=fr.ird.observe.entities.referentiel.Species|\ -Select distinct tl.species \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetSample ts \ -Join ts.targetLength tl \ -Where t.id = :tripId \ -And tl.measureType = 2 \ -And ts.discarded = true -report.targetDiscardedDistributionLengthsLF.request.1=0,0|row| \ -Select tl.length , Sum(tl.count) \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetSample ts \ -Join ts.targetLength tl \ -Where t.id = :tripId \ - And tl.species.id = :speciesId \ - And tl.measureType = 2 \ - And ts.discarded = true \ -Group By tl.length \ -Order By tl.length - -############################################ -## Répartition des calées par cuves -############################################ - -report.repartionCaleeParCuve.name=R\u00e9partition des cal\u00e9es par cuves -report.repartionCaleeParCuve.description=R\u00e9partition des cal\u00e9es par cuves, type de banc et esp\u00e8ce -report.repartionCaleeParCuve.columns=Jour - Heure observation,Latitude,Longitude,Type de banc,Esp\u00e8ce,Tonnage,Cuve -report.repartionCaleeParCuve.request.1=0,0|row| \ -Select concat(day(r.date), '/', month(r.date), '/', year(r.date), ' ', hour(a.time), ':', minute(a.time)), \ - a.latitude, \ - a.longitude, \ - case when a.setSeine.schoolType = 1 then 'BO' else 'BL' end, \ - tc.weightCategory.species.faoCode, \ - Sum(tc.catchWeight), \ - case when tc.discarded = true then 'Rejet\u00e9' else tc.well end \ -From TripSeineImpl t \ -Join t.route r \ -Join r.activitySeine a \ -Join a.setSeine.targetCatch tc \ -Where t.id = :tripId \ -Group By r.date, a.time, a.latitude, a.longitude, tc.weightCategory.species, tc.weightCategory.species.faoCode, tc.well, a.setSeine.schoolType \ -Order By r.date, a.time, tc.weightCategory.species, tc.well diff --git a/observe-business/src/main/java/fr/ird/converter/FloatConverter.java b/observe-business/src/main/java/fr/ird/converter/FloatConverter.java deleted file mode 100644 index 0ca73a8..0000000 --- a/observe-business/src/main/java/fr/ird/converter/FloatConverter.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * #%L - * MS-Access Importer - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2010 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.converter; - -import org.apache.commons.beanutils.ConversionException; -import org.nuiton.converter.NuitonConverter; - -import static org.nuiton.i18n.I18n.t; - -/** - * A float converter which is not dependant on user locale to obtain the locale - * {@code dot} representation. - * <p/> - * It can transform {@code 0.2} and also {@code 0, 2}. - * - * @author tchemit - chemit@codelutin.com - * @since 1.3 - */ -public class FloatConverter implements NuitonConverter { - - @Override - public Object convert(Class aClass, Object value) { - if (value == null) { - throw new ConversionException( - t("nuitonutil.error.convertor.noValue", this)); - } - if (isEnabled(aClass)) { - Object result; - if (isEnabled(value.getClass())) { - result = value; - return result; - } - if (value instanceof String) { - result = valueOf((String) value); - return result; - } - } - throw new ConversionException( - t("nuitonutil.error.no.convertor", aClass.getName(), value)); - } - - protected Float valueOf(String value) { - try { - if (value.contains(",")) { - value = value.replaceAll(",", "."); - } - Float result; - result = Float.valueOf(value); - return result; - } catch (NumberFormatException e) { - throw new ConversionException( - t("nuitonutil.error.float.convertor", value, this, e.getMessage())); - } - } - - - protected boolean isEnabled(Class<?> aClass) { - return Float.class.equals(aClass); - } - - @Override - public Class<Float> getType() { - return Float.class; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/BinderService.java b/observe-business/src/main/java/fr/ird/observe/BinderService.java deleted file mode 100644 index ec23806..0000000 --- a/observe-business/src/main/java/fr/ird/observe/BinderService.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.TopiaEntityBinder; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; -import org.nuiton.util.beans.BinderModelBuilder; - -/** - * Service d'utilisation des binders - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class BinderService { - - public <E extends TopiaEntity> BinderModelBuilder<E, E> newBinderBuilder(Class<E> type, String... properties) { - BinderModelBuilder<E, E> builder = BinderModelBuilder.newEmptyBuilder(type); - builder.addSimpleProperties(properties); - return builder; - } - - public <E extends TopiaEntity> TopiaEntityBinder<E> getTopiaBinder(Class<E> entityClass, - String contextName) { - if (ObserveBinderHelper.getCachedBinderModel(entityClass, entityClass, contextName) == null) { - - // we do not want to have auto created binder model by the factory - return null; - } - return (TopiaEntityBinder<E>) ObserveBinderHelper.newBinder(entityClass, entityClass, contextName, TopiaEntityBinder.class); - } - - public <E extends TopiaEntity> TopiaEntityBinder<E> registerTopiaBinder(Class<E> entityClass, - BinderModelBuilder<E, E> builder, - String contextName) { - return ObserveBinderHelper.registerTopiaBinder(entityClass, builder, contextName); - } - - public <E extends TopiaEntity> TopiaEntityBinder<E> getSimpleTopiaBinder(Class<E> entityClass) { - return getTopiaBinder(entityClass, "Observe"); - } - - public <E extends TopiaEntity> void simpleCopy(E source, E target, boolean tech) { - Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(ObserveDAOHelper.getContracts(), target.getClass()); - TopiaEntityBinder<E> binder = getSimpleTopiaBinder(entityClass); - if (binder == null) { - throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass()); - } - binder.load(source, target, tech); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/ConsolidateDataService.java b/observe-business/src/main/java/fr/ird/observe/ConsolidateDataService.java deleted file mode 100644 index 39cd13d..0000000 --- a/observe-business/src/main/java/fr/ird/observe/ConsolidateDataService.java +++ /dev/null @@ -1,883 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Collections2; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.entities.LengthWeightComputable; -import fr.ird.observe.entities.constants.seine.NonTargetCatchComputedValueSource; -import fr.ird.observe.entities.constants.seine.SchoolType; -import fr.ird.observe.entities.referentiel.LengthWeightParameter; -import fr.ird.observe.entities.referentiel.Ocean; -import fr.ird.observe.entities.referentiel.Sex; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.NonTargetCatch; -import fr.ird.observe.entities.seine.NonTargetLength; -import fr.ird.observe.entities.seine.NonTargetSample; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TargetLength; -import fr.ird.observe.entities.seine.TargetSample; -import fr.ird.observe.entities.seine.TripSeine; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; -import org.nuiton.topia.persistence.util.TopiaEntityRef; -import org.nuiton.util.beans.BeanMonitor; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le service pour consolider les données observers. - * <p/> - * Il s'agit de pouvoir calculer le type de banc d'une activité et de calculer - * les données déductibles des données observées (sur les discardeds faune et les - * échantillons via les relations taille-weight et autres...). - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.8 - */ -public class ConsolidateDataService { - - /** Logger */ - private static final Log log = - LogFactory.getLog(ConsolidateDataService.class); - - private static final String MESSAGE_FORMAT_3 = - "[%1$s] %2$s calculé : %3$s (%4$s:%5$s, %6$s:%7$s)"; - - protected final BeanMonitor targetLengthMonitor = new BeanMonitor( - TargetLength.PROPERTY_LENGTH, - TargetLength.PROPERTY_LENGTH_SOURCE, - TargetLength.PROPERTY_WEIGHT, - TargetLength.PROPERTY_WEIGHT_SOURCE); - - protected final BeanMonitor nonTargetSampleMonitor = new BeanMonitor( - NonTargetLength.PROPERTY_LENGTH, - NonTargetLength.PROPERTY_LENGTH_SOURCE, - NonTargetLength.PROPERTY_WEIGHT, - NonTargetLength.PROPERTY_WEIGHT_SOURCE); - - protected final BeanMonitor nonTargetCatchMonitor = new BeanMonitor( - NonTargetCatch.PROPERTY_MEAN_LENGTH, - NonTargetCatch.PROPERTY_MEAN_LENGTH_COMPUTED_SOURCE, - NonTargetCatch.PROPERTY_MEAN_WEIGHT, - NonTargetCatch.PROPERTY_MEAN_WEIGHT_COMPUTED_SOURCE, - NonTargetCatch.PROPERTY_CATCH_WEIGHT, - NonTargetCatch.PROPERTY_CATCH_WEIGHT_COMPUTED_SOURCE, - NonTargetCatch.PROPERTY_TOTAL_COUNT, - NonTargetCatch.PROPERTY_TOTAL_COUNT_COMPUTED_SOURCE - ); - - protected Decorator<TripSeine> mareeDecorator; - - protected Decorator<Species> speciesDecorator; - - protected Decorator<ActivitySeine> activityDecorator; - - protected String nonTargetCatcheLabel; - - protected String speciesLabel; - - protected String speciesThonLabel; - - protected final SendMessageAble LOG_MESSAGER = new SendMessageAble() { - - @Override - public void sendMessage(String message) { - if (log.isInfoEnabled()) { - log.info(message); - } - } - }; - - public String getNonTargetCatcheLabel() { - if (nonTargetCatcheLabel == null) { - nonTargetCatcheLabel = t(DecoratorService.getEntityLabel(NonTargetCatch.class)); - } - return nonTargetCatcheLabel; - } - - public String getSpeciesLabel() { - if (speciesLabel == null) { - speciesLabel = t(DecoratorService.getEntityLabel(Species.class)); - } - return speciesLabel; - - } - - public String decorate(TripSeine maree) { - if (mareeDecorator == null) { - mareeDecorator = getDecoratorService().getDecoratorByType(TripSeine.class); - } - return mareeDecorator.toString(maree); - } - - public String decorate(Species species) { - if (speciesDecorator == null) { - speciesDecorator = - getDecoratorService().getDecoratorByType(Species.class); - } - return speciesDecorator.toString(species); - } - - public String decorate(ActivitySeine activitySeine) { - if (activityDecorator == null) { - activityDecorator = - getDecoratorService().getDecoratorByType(ActivitySeine.class); - } - return activityDecorator.toString(activitySeine); - } - - public boolean consolidateTrip(SendMessageAble messager, - TopiaContext tx, - TripSeine maree) throws Exception { - String mareeStr = decorate(maree); - - SendMessageAble messager1 = getMessager(messager); - messager1.sendMessage( - t("observe.message.consolidate.start.maree", mareeStr)); - - // recuperation des ids des sets de la maree - String[] activityIds = getActivityIds(maree); - - if (activityIds.length == 0) { - - // pas de set dans cette maree, donc rien a sauvegarder - messager1.sendMessage( - t("observe.message.consolidate.no.activity.from.maree", - mareeStr)); - return false; - } - - // recuperation des references vers les activitys avec set - SortedMap<TopiaEntity, List<TopiaEntityRef>> result; - - result = TopiaEntityHelper.detectReferences( - ObserveDAOHelper.getContracts(), activityIds, maree); - - List<ActivitySeine> toUpdate = new ArrayList<ActivitySeine>(result.size()); - for (Map.Entry<TopiaEntity, List<TopiaEntityRef>> e : - result.entrySet()) { - ActivitySeine activitySeine = (ActivitySeine) e.getKey(); - List<TopiaEntityRef> refs = e.getValue(); - TopiaEntityRef ref = refs.get(0); - TopiaEntity[] path = ref.getPath(); - Route route = (Route) path[path.length - 2]; - boolean needUpdate = consolidateActivity(messager, - tx, - maree, - route, - activitySeine - ); - if (needUpdate) { - toUpdate.add(activitySeine); - } - } - if (toUpdate.isEmpty()) { - - // rien n'a ete modifie - messager1.sendMessage(t("observe.message.consolidate.nothing.to.save.for.maree", - mareeStr)); - return false; - } - - // on devra mettre a jour en base la maree - messager1.sendMessage(t("observe.message.consolidate.maree.need.update", - mareeStr)); - return true; - } - - public void clear() { - - nonTargetSampleMonitor.setBean(null); - targetLengthMonitor.setBean(null); - nonTargetCatchMonitor.setBean(null); - mareeDecorator = null; - activityDecorator = null; - speciesDecorator = null; - nonTargetCatcheLabel = null; - speciesLabel = null; - speciesThonLabel = null; - } - - protected boolean consolidateActivity(SendMessageAble messager, - TopiaContext tx, - TripSeine maree, - Route route, - ActivitySeine activity) throws Exception { - - getMessager(messager).sendMessage(t("observe.message.consolidate.start.activity", - decorate(activity))); - - boolean needUpdate = false; - SetSeine set = activity.getSetSeine(); - SchoolType oldTypeBanc = set.getSchoolType(); - SchoolType newTypeBanc = activity.getSchoolType(); - if (oldTypeBanc == null || oldTypeBanc != newTypeBanc) { - - // le type de banc a change, on doit sauver l'activity - needUpdate = true; - set.setSchoolType(newTypeBanc); - } - - if (!set.isTargetSampleEmpty()) { - - // des echantillons thons trouves - for (TargetSample targetSample : set.getTargetSample()) { - if (!targetSample.isTargetLengthEmpty()) { - for (TargetLength targetLength : - targetSample.getTargetLength()) { - - targetLengthMonitor.setBean(targetLength); - - updateLengthWeightAble( - tx, - maree, - route.getDate(), - targetLength.getSpecies(), - null, // pas de gender precise - targetLength - ); - - if (targetLengthMonitor.wasModified()) { - needUpdate = true; - } - } - } - } - } - - if (!set.isNonTargetSampleEmpty()) { - - // des echantillons faunes trouves - for (NonTargetSample nonTargetSample : - set.getNonTargetSample()) { - - if (!nonTargetSample.isNonTargetLengthEmpty()) { - for (NonTargetLength nonTargetLength : - nonTargetSample.getNonTargetLength()) { - - nonTargetSampleMonitor.setBean(nonTargetLength); - - updateLengthWeightAble( - tx, - maree, - route.getDate(), - nonTargetLength.getSpecies(), - nonTargetLength.getSex(), - nonTargetLength - ); - if (nonTargetSampleMonitor.wasModified()) { - needUpdate = true; - } - } - } - } - } - - if (!set.isNonTargetCatchEmpty()) { - - // des captures (ou rejets) faunes trouves - for (NonTargetCatch nonTargetCatch : set.getNonTargetCatch()) { - - nonTargetCatchMonitor.setBean(nonTargetCatch); - - // suppression de tous les champs précédemment calculés - - if (nonTargetCatch.isCatchWeightComputed()) { - nonTargetCatch.setCatchWeight(null); - nonTargetCatch.setCatchWeightComputedSource(null); - } - - if (nonTargetCatch.isTotalCountComputed()) { - nonTargetCatch.setTotalCount(null); - nonTargetCatch.setTotalCountComputedSource(null); - } - - if (nonTargetCatch.isMeanWeightComputed()) { - nonTargetCatch.setMeanWeight(null); - nonTargetCatch.setMeanWeightComputedSource(null); - } - - if (nonTargetCatch.isMeanLengthComputed()) { - nonTargetCatch.setMeanLength(null); - nonTargetCatch.setMeanLengthComputedSource(null); - } - - updateNonTargetCatch( - tx, - maree, - set, - route.getDate(), - nonTargetCatch - ); - - if (nonTargetCatchMonitor.wasModified()) { - needUpdate = true; - } - } - } - return needUpdate; - } - - protected boolean allNonTargetCatchDataFilled(NonTargetCatch nonTargetCatch) { - return Iterables.all( - Sets.newHashSet(nonTargetCatch.getCatchWeight(), - nonTargetCatch.getTotalCount(), - nonTargetCatch.getMeanWeight(), - nonTargetCatch.getMeanLength()), - Predicates.notNull()); - } - - protected void updateNonTargetCatch(TopiaContext tx, - TripSeine maree, - SetSeine set, - Date jour, - NonTargetCatch nonTargetCatch) throws DataSourceException { - - final Species species = nonTargetCatch.getSpecies(); - - // récupération du référentiel - LengthWeightParameter parametrage = - getDataService().findLengthWeightParameter(tx, - species, - maree.getOcean(), - null, // pas de sexe spécifié - jour); - - // -- Cas n°1 (calcul uniquement à partir des relations taille - poids) - updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); - - if (allNonTargetCatchDataFilled(nonTargetCatch)) { - - // tout est rempli, plus rien à faire - return; - } - - // répération des échantillon de cette espèce sur les calée - - Collection<NonTargetLength> samples = null; - - if (!set.isNonTargetSampleEmpty()) { - samples = Collections2.filter(set.getNonTargetSample().iterator().next().getNonTargetLength(), new Predicate<NonTargetLength>() { - - @Override - public boolean apply(NonTargetLength input) { - return species.equals(input.getSpecies()); - } - }); - } - - - if (nonTargetCatch.getCatchWeight() != null || nonTargetCatch.getTotalCount() != null) { - - // -- Cas n°2 (pas de taille / poids moyen mais au moins un des deux taille / poids) - computeNonTargetCatchTailleMoyenne(nonTargetCatch, samples, parametrage); - } - - if (allNonTargetCatchDataFilled(nonTargetCatch)) { - - // tout est rempli, plus rien à faire - return; - } - - // -- Cas n°3 (pas de nombre estimé) - - if (nonTargetCatch.getTotalCount() == null) { - - computeNonTargetCatchNombreEstime(nonTargetCatch, samples, parametrage); - - } - - if (allNonTargetCatchDataFilled(nonTargetCatch)) { - - // tout est rempli, plus rien à faire - return; - } - - // -- Cas n°4 (pas de poids moyen, taille moyenne) - - computeNonTargetCatchMeanValues(nonTargetCatch, parametrage); - } - - protected void updateNonTargetCatchByLengthWeightRelation(NonTargetCatch nonTargetCatch, - LengthWeightParameter parametrage) throws DataSourceException { - - // calcul via le paramétrage taille - poids - updateLengthWeightAble( - nonTargetCatch.getSpecies(), - nonTargetCatch, - parametrage - ); - - // calcule l'un des trois champs poids estimé - nbEstime - poids moyen - updateNonTargetCatchPoidsEstimeNbEstimePoidsMoyen(nonTargetCatch); - - // on ressaye d'appliquer la relation taille - poids au cas où une des - // trois valeurs précédentes a été calculée, on pourrait peut-être - // ainsi en déduire via le paramétrage la taille moyenne - updateLengthWeightAble( - nonTargetCatch.getSpecies(), - nonTargetCatch, - parametrage - ); - } - - protected void computeNonTargetCatchTailleMoyenne(NonTargetCatch nonTargetCatch, - Collection<NonTargetLength> samples, - LengthWeightParameter parametrage) throws DataSourceException { - - Float meanLength = nonTargetCatch.getMeanLength(); - - if (meanLength == null) { - - // on essaye de calculer la taille moyenne à partir des échantillons - - NonTargetCatchComputedValueSource computedSource = null; - - if (CollectionUtils.isNotEmpty(samples)) { - - // on calcul la taille moyenne à partir des échantillons - float totalLength = 0f; - int totalCount = 0; - for (NonTargetLength sample : samples) { - - Integer count = sample.getCount(); - Float length = sample.getLength(); - - if (count != null && length != null) { - totalCount += count; - totalLength += length * count; - } - } - - if (totalCount != 0) { - - meanLength = totalLength / totalCount; - - computedSource = NonTargetCatchComputedValueSource.FROM_SAMPLE; - } - } - - if (meanLength == null && parametrage != null) { - - // on prend directement la valeur fournie par le référentiel - - meanLength = parametrage.getMeanLength(); - computedSource = NonTargetCatchComputedValueSource.FROM_REFERENTIEL; - } - - if (meanLength != null) { - - // la taille moyenne a pu etre calculee, on la pousse alors - nonTargetCatch.setMeanLength(meanLength); - nonTargetCatch.setMeanLengthComputedSource(computedSource); - - } - - } - - if (meanLength != null) { - - // on peut aussi relancer la calcul du cas n°1 - updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); - - } - - } - - private void computeNonTargetCatchNombreEstime(NonTargetCatch nonTargetCatch, - Collection<NonTargetLength> samples, - LengthWeightParameter parametrage) throws DataSourceException { - - - Integer totalCount = nonTargetCatch.getTotalCount(); - - if (totalCount == null) { - - if (CollectionUtils.isNotEmpty(samples)) { - - // on calcul la nombre d'individus à partir des échantillons - totalCount = 0; - for (NonTargetLength sample : samples) { - - Integer count = sample.getCount(); - - if (count != null) { - totalCount += count; - } - } - - if (totalCount != 0) { - - nonTargetCatch.setTotalCount(totalCount); - nonTargetCatch.setTotalCountComputedSource(NonTargetCatchComputedValueSource.FROM_SAMPLE); - - - } - } - - } - - if (nonTargetCatch.getMeanWeight() != null || nonTargetCatch.getMeanLength() != null) { - - // on peut aussi relancer la calcul du cas n°1 - updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); - } - - } - - private void computeNonTargetCatchMeanValues(NonTargetCatch nonTargetCatch, - LengthWeightParameter parametrage) throws DataSourceException { - - if (parametrage != null) { - - if (nonTargetCatch.getMeanLength() == null) { - nonTargetCatch.setMeanLength(parametrage.getMeanLength()); - nonTargetCatch.setMeanLengthComputedSource(NonTargetCatchComputedValueSource.FROM_REFERENTIEL); - } - - if (nonTargetCatch.getMeanWeight() == null) { - nonTargetCatch.setMeanWeight(parametrage.getMeanWeight()); - nonTargetCatch.setMeanWeightComputedSource(NonTargetCatchComputedValueSource.FROM_REFERENTIEL); - } - - if (nonTargetCatch.getMeanWeight() != null || nonTargetCatch.getMeanLength() != null) { - - // on peut aussi relancer la calcul du cas n°1 - updateNonTargetCatchByLengthWeightRelation(nonTargetCatch, parametrage); - } - - } - } - - protected void updateNonTargetCatchPoidsEstimeNbEstimePoidsMoyen(NonTargetCatch nonTargetCatch) throws DataSourceException { - - Float meanWeight = nonTargetCatch.getMeanWeight(); - Float catchWeight = nonTargetCatch.getCatchWeight(); - Integer totalCount = nonTargetCatch.getTotalCount(); - - String entityLabel = getNonTargetCatcheLabel(); - - if (catchWeight == null && totalCount != null && meanWeight != null) { - - // calcul le weight poids à partir de nb estime et du poids moyen - catchWeight = meanWeight * (float) totalCount / 1000; - nonTargetCatch.setCatchWeight(catchWeight); - nonTargetCatch.setCatchWeightComputedSource(NonTargetCatchComputedValueSource.FROM_DATA); - String message = String.format(MESSAGE_FORMAT_3, - entityLabel, - t("observe.common.catchWeight"), - catchWeight, - t("observe.common.meanWeight"), - meanWeight, - t("observe.common.totalCount"), - totalCount); - if (log.isInfoEnabled()) { - log.info(message); - } - } - - if (totalCount == null && catchWeight != null && meanWeight != null) { - - // calcul le nb estime à partir du poids estime et du poids moyen - totalCount = (int) ((float) 1000 * catchWeight / meanWeight); - nonTargetCatch.setTotalCount(totalCount); - nonTargetCatch.setTotalCountComputedSource(NonTargetCatchComputedValueSource.FROM_DATA); - String message = String.format(MESSAGE_FORMAT_3, - entityLabel, - t("observe.common.totalCount"), - totalCount, - t("observe.common.meanWeight"), - meanWeight, - t("observe.common.catchWeight"), - catchWeight); - if (log.isInfoEnabled()) { - log.info(message); - } - } - - if (meanWeight == null && totalCount != null && totalCount != 0 && catchWeight != null && - !NonTargetCatchComputedValueSource.FROM_SAMPLE.equals(nonTargetCatch.getTotalCountComputedSource())) { - - // calcul le poids moyen à partir de nb estime et du poids estime - // uniquement si le nombre estimé ne vient pas des échantillons (voir http://forge.codelutin.com/issues/4670) - - meanWeight = catchWeight * (float) 1000 / (float) totalCount; - nonTargetCatch.setMeanWeight(meanWeight); - nonTargetCatch.setMeanWeightComputedSource(NonTargetCatchComputedValueSource.FROM_DATA); - String message = String.format(MESSAGE_FORMAT_3, - entityLabel, - t("observe.common.meanWeight"), - meanWeight, - t("observe.common.totalCount"), - totalCount, - t("observe.common.catchWeight"), - catchWeight); - if (log.isInfoEnabled()) { - log.info(message); - } - } - } - - protected void updateLengthWeightAble(TopiaContext tx, - TripSeine maree, - Date jour, - Species species, - Sex sex, - LengthWeightComputable e) throws DataSourceException { - - Ocean ocean = maree.getOcean(); - - String entityLabel = getSpeciesLabel(); - - Float weight = e.getWeight(); - Float length = e.getLength(); - - boolean computeWeight = false; - boolean computeLength = false; - - if (weight == null && length != null) { - - // on essaye de calculer le poids - computeWeight = true; - } - - if (length == null && weight != null) { - - // on essaye de calcule la taille - computeLength = true; - } - - if (!computeLength && !computeWeight) { - - // rien a calculer - return; - } - - // recherche du parametrage adequate - LengthWeightParameter parametrage = - getDataService().findLengthWeightParameter( - tx, - species, - ocean, - sex, - jour - ); - - if (parametrage == null) { - - // aucun parametrage connu - - String message = t("observe.message.consolidate.no.parametrage.found", - t(entityLabel), - decorate(species) - ); - if (log.isWarnEnabled()) { - log.warn(message); - } - return; - } - - if (computeLength) { - Float newLength = parametrage.computeLength(weight); - if (newLength != null) { - - // la taille a ete calculee - String message = - "[" + t(entityLabel) + "] " + - t("observe.message.consolidate.computed.taille", - newLength, - weight, - parametrage.getWeightLengthFormula(), - parametrage.getCoefficients() - ); - if (log.isInfoEnabled()) { - log.info(message); - } - e.setLength(newLength); - e.setLengthSource(true); - return; - } - - // la taille n'a pas ete changee, on peut quitter car il est impossible - // de calculer et la taille et le poids... - return; - } - - // on cherche obligatoirement a calculer le poids - Float newWeight = parametrage.computeWeight(length); - if (newWeight != null) { - - // le poids a ete calcule - String message = "[" + t(entityLabel) + "] " + - t("observe.message.consolidate.computed.weight", - newWeight, - length, - parametrage.getLengthWeightFormula(), - parametrage.getCoefficients()); - if (log.isInfoEnabled()) { - log.info(message); - } - e.setWeight(newWeight); - e.setWeightSource(true); - } - } - - protected void updateLengthWeightAble(Species species, - LengthWeightComputable e, - LengthWeightParameter parametrage) throws DataSourceException { - - String entityLabel = getSpeciesLabel(); - - Float weight = e.getWeight(); - boolean computeWeight = false; - boolean computeLength = false; - Float length = e.getLength(); - - if (weight == null && length != null) { - - // on essaye de calculer le poids - computeWeight = true; - } - - if (length == null && weight != null) { - - // on essaye de calcule la taille - computeLength = true; - } - - if (!computeLength && !computeWeight) { - - // rien a calculer - return; - } - - if (parametrage == null) { - - // aucun parametrage connu - - String message = t("observe.message.consolidate.no.parametrage.found", - t(entityLabel), - decorate(species) - ); - if (log.isWarnEnabled()) { - log.warn(message); - } - return; - } - - if (computeLength) { - Float newLength = parametrage.computeLength(weight); - if (newLength != null) { - - // la taille a ete calculee - String message = - "[" + t(entityLabel) + "] " + - t("observe.message.consolidate.computed.taille", - newLength, - weight, - parametrage.getWeightLengthFormula(), - parametrage.getCoefficients() - ); - if (log.isInfoEnabled()) { - log.info(message); - } - e.setLength(newLength); - e.setLengthSource(true); - return; - } - - // la taille n'a pas ete changee, on peut quitter car il est impossible - // de calculer et la taille et le poids... - return; - } - - // on cherche obligatoirement a calculer le poids - Float newWeight = parametrage.computeWeight(length); - if (newWeight != null) { - - // le weight a ete calcule - String message = "[" + t(entityLabel) + "] " + - t("observe.message.consolidate.computed.weight", - newWeight, - length, - parametrage.getLengthWeightFormula(), - parametrage.getCoefficients()); - if (log.isInfoEnabled()) { - log.info(message); - } - e.setWeight(newWeight); - e.setWeightSource(true); - } - } - - protected String[] getActivityIds(TripSeine maree) { - List<String> tmpIds = new ArrayList<String>(); - if (!maree.isRouteEmpty()) { - for (Route route : maree.getRoute()) { - if (!route.isActivitySeineEmpty()) { - for (ActivitySeine activitySeine : route.getActivitySeine()) { - if (activitySeine.getSetSeine() != null) { - - // on ne retient que les activitys avec set - tmpIds.add(activitySeine.getTopiaId()); - } - } - } - } - } - String[] result = tmpIds.toArray(new String[tmpIds.size()]); - return result; - } - - protected DataService getDataService() { - DataService service = ObserveServiceHelper.getDataService(); - return service; - } - - protected DecoratorService getDecoratorService() { - DecoratorService service = ObserveServiceHelper.getDecoratorService(); - return service; - } - - protected SendMessageAble getMessager(SendMessageAble messager) { - return messager == null ? LOG_MESSAGER : messager; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/DataService.java b/observe-business/src/main/java/fr/ird/observe/DataService.java deleted file mode 100644 index 98a5512..0000000 --- a/observe-business/src/main/java/fr/ird/observe/DataService.java +++ /dev/null @@ -1,2606 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.db.constants.DataSourceState; -import fr.ird.observe.db.util.TopiaExecutor; -import fr.ird.observe.db.util.TopiaExecutor2; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.EntityMap; -import fr.ird.observe.entities.OpenableEntities; -import fr.ird.observe.entities.OpenableEntity; -import fr.ird.observe.entities.Trip; -import fr.ird.observe.entities.constants.GearType; -import fr.ird.observe.entities.constants.ReferenceLocale; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.ActivityLonglineDAO; -import fr.ird.observe.entities.longline.ActivityLonglines; -import fr.ird.observe.entities.longline.Basket; -import fr.ird.observe.entities.longline.Branchline; -import fr.ird.observe.entities.longline.CatchLongline; -import fr.ird.observe.entities.longline.GearUseFeaturesLongline; -import fr.ird.observe.entities.longline.GearUseFeaturesMeasurementLongline; -import fr.ird.observe.entities.longline.GearUseFeaturesMeasurementLonglineImpl; -import fr.ird.observe.entities.longline.Section; -import fr.ird.observe.entities.longline.SensorUsed; -import fr.ird.observe.entities.longline.SizeMeasure; -import fr.ird.observe.entities.longline.SizeMeasureImpl; -import fr.ird.observe.entities.longline.Tdr; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.longline.TripLonglineDAO; -import fr.ird.observe.entities.longline.WeightMeasure; -import fr.ird.observe.entities.longline.WeightMeasureImpl; -import fr.ird.observe.entities.referentiel.Gear; -import fr.ird.observe.entities.referentiel.GearCaracteristic; -import fr.ird.observe.entities.referentiel.LengthWeightParameter; -import fr.ird.observe.entities.referentiel.LengthWeightParemeterHelper; -import fr.ird.observe.entities.referentiel.Ocean; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.referentiel.ProgramDAO; -import fr.ird.observe.entities.referentiel.ReferenceEntities; -import fr.ird.observe.entities.referentiel.Sex; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.referentiel.SpeciesList; -import fr.ird.observe.entities.referentiel.SpeciesListDAO; -import fr.ird.observe.entities.referentiel.longline.SensorType; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.ActivitySeineDAO; -import fr.ird.observe.entities.seine.ActivitySeines; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.FloatingObjectDAO; -import fr.ird.observe.entities.seine.GearUseFeaturesMeasurementSeine; -import fr.ird.observe.entities.seine.GearUseFeaturesMeasurementSeineImpl; -import fr.ird.observe.entities.seine.GearUseFeaturesSeine; -import fr.ird.observe.entities.seine.NonTargetCatch; -import fr.ird.observe.entities.seine.NonTargetLength; -import fr.ird.observe.entities.seine.NonTargetSample; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.RouteDAO; -import fr.ird.observe.entities.seine.Routes; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TargetCatch; -import fr.ird.observe.entities.seine.TargetLength; -import fr.ird.observe.entities.seine.TargetSample; -import fr.ird.observe.entities.seine.TripSeine; -import fr.ird.observe.entities.seine.TripSeineDAO; -import fr.ird.observe.tripMap.TripMapPoint; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.event.TopiaTransactionEvent; -import org.nuiton.topia.event.TopiaTransactionListener; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaId; -import org.nuiton.topia.persistence.util.DiffState; -import org.nuiton.topia.persistence.util.EntityOperator; -import org.nuiton.topia.persistence.util.Loador; -import org.nuiton.topia.persistence.util.TopiaEntityBinder; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeListenerProxy; -import java.beans.PropertyChangeSupport; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le contrat du service de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataService { - - /** Logger */ - private static final Log log = LogFactory.getLog(DataService.class); - - String PARENT_BEAN = "parentBean"; - - String BEAN = "bean"; - - protected DecoratorService decoratorService; - - protected DataContext dataContext; - - protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - private boolean skipTransactionListener; - - private TopiaTransactionListener transactionListener = new TopiaTransactionListener() { - - public void commit(TopiaTransactionEvent event) { - - if (skipTransactionListener) { - return; - } - - java.util.Set<TopiaEntity> entities = event.getEntities(); - - // pour recenser les referentiels modifies - EnumSet<ObserveEntityEnum> referentiel = - EnumSet.noneOf(ObserveEntityEnum.class); - - // pour referencer les types openables modifies - boolean touchOpenContext = false; - - // pour referencer les donnees observers modifiees - java.util.Set<TopiaEntity> data = new HashSet<TopiaEntity>(); - - for (TopiaEntity entity : entities) { - if (log.isDebugEnabled()) { - if (event.isLoad(entity)) { - - if (log.isDebugEnabled()) { - log.debug("loaded entity [" + entity.getTopiaId() + "]"); - } - } else if (event.isCreate(entity)) { - if (log.isInfoEnabled()) { - log.info("created entitiy [" + entity.getTopiaId() + "]"); - } - - } else if (event.isUpdate(entity)) { - if (log.isDebugEnabled()) { - log.debug("updated entitiy [" + entity.getTopiaId() + "]"); - } - - } else if (event.isDelete(entity)) { - if (log.isDebugEnabled()) { - log.debug("deleted entitiy [" + entity.getTopiaId() + "]"); - } - } - } - - if (!event.isModification(entity)) { - - // pas de modification, on ne fait rien - continue; - } - - // l'entite a ete modifiee, cree ou supprimee - ObserveEntityEnum constant = - ObserveEntityEnum.valueOf(entity); - - if (constant == null) { - - // non gere (peut-etre une entite technique) - continue; - } - - if (Entities.isReferentielClass(constant)) { - - // c'est un objet du référentiel - referentiel.add(constant); - continue; - } - - // il s'agit d'une donnée utilisateur - data.add(entity); - - if (OpenableEntities.isOpenable(entity)) { - touchOpenContext = true; - } - } - - DataSource source = ObserveServiceHelper.get().getDataSource(); - if (source == null) { - throw new IllegalStateException("No source service registred."); - } - source.checkState(DataSourceState.OPEN); - - if (!referentiel.isEmpty()) { - - // notification de modification de reférentiels - fireReferentielChanged( - source, - referentiel.toArray( - new ObserveEntityEnum[referentiel.size()]) - ); - } - - if (!data.isEmpty()) { - - // notification de modification de reférentiels - fireDataChanged(source, - data.toArray(new TopiaEntity[data.size()]) - ); - } - - if (touchOpenContext) { - fireOpenChanged(source); - } - } - - - public void rollback(TopiaTransactionEvent event) { - } - }; - - protected PropertyChangeListener openListener = new PropertyChangeListener() { - - public void propertyChange(PropertyChangeEvent evt) { - DataService source = (DataService) evt.getSource(); - DataContext dataContext = source.getDataContext(); - String[] value = (String[]) evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug("open context changed in data service, will propagate it to " + dataContext); - log.debug("new open ids : " + Arrays.toString(value)); - } - dataContext.populateOpens(value); - } - }; - - - public void registerDataSource(DataSource source) { - - ObserveServiceHelper.get().setDataSource(source); - - addPropertyChangeListener(DataSource.OPEN_PROPERTY_KEY, openListener); - } - - - public void unregisterDataSource(DataSource source) { - - ObserveServiceHelper.get().setDataSource(null); - - removePropertyChangeListener(DataSource.OPEN_PROPERTY_KEY, openListener); - - // remove all listeners for the referentiel - //FIXMe tchemit 2010-11-30 Perharps we should remove all listeners ? - removeReferentielPropertyChangeListeners(); - } - - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveServiceHelper.getDecoratorService(); - } - return decoratorService; - } - - - public DataContext getDataContext() { - if (dataContext == null) { - dataContext = ObserveServiceHelper.getDataContext(); - } - return dataContext; - } - - // ------------------------------------------------------------------------ - // -- Méthodes de gestion des transactions - // ------------------------------------------------------------------------ - - - public TopiaContext beginTransaction(DataSource source, - String methodName) throws DataSourceException { - source.checkState(DataSourceState.OPEN); - if (log.isDebugEnabled()) { - log.debug("begin tx " + methodName); - } - TopiaContext tx = source.beginTransaction(methodName); - tx.addTopiaTransactionListener(transactionListener); - if (log.isDebugEnabled()) { - log.debug("after begin tx " + methodName); - } - return tx; - } - - - public void rollbackTransaction(DataSource source, - TopiaContext tx, - String txName) throws DataSourceException { - source.checkState(DataSourceState.OPEN); - source.rollbackTransaction(tx, txName); - } - - - public void commitTransaction(DataSource source, - TopiaContext tx, - String txName) throws DataSourceException { - source.checkState(DataSourceState.OPEN); - if (log.isDebugEnabled()) { - log.debug("commit tx " + txName); - } - source.commitTransaction(tx, txName); - if (log.isDebugEnabled()) { - log.debug("after commit tx " + txName); - } - } - - - public void closeTransaction(DataSource source, - TopiaContext tx, - String txName) throws DataSourceException { - source.checkState(DataSourceState.OPEN); - if (log.isDebugEnabled()) { - log.debug("close tx " + txName); - } - tx.removeTopiaTransactionListener(transactionListener); - source.closeTransaction(tx, txName); - if (log.isDebugEnabled()) { - log.debug("after close tx " + txName); - } - } - - // ------------------------------------------------------------------------ - // -- Méthodes métiers de récupération de données - // ------------------------------------------------------------------------ - - - public String[] getOpenIds(DataSource source) throws DataSourceException { - - String[] result = null; - TopiaContext tx = beginTransaction(source, "getOpenIds"); - try { - - result = source.getOpenIds(tx); - } finally { - closeTransaction(source, tx, "getOpenIds"); - } - return result; - } - - - public <E extends TopiaEntity> List<E> getList(DataSource source, - Class<E> klass) throws DataSourceException { - - List<E> list = getList(source, klass, null, null); - return list; - } - - - public <E extends TopiaEntity> List<E> getList(DataSource source, Class<E> klass, Predicate<E> predicate) throws DataSourceException { - List<E> result = getList(source, klass, predicate, null); - return result; - } - - - public <E extends TopiaEntity> List<E> getList(DataSource source, - Class<E> klass, - TopiaEntityBinder<E> loador) throws DataSourceException { - List<E> result = getList(source, klass, null, loador); - return result; - } - - - public <E extends TopiaEntity> List<E> getList(DataSource source, - Class<E> klass, - Predicate<E> predicate, - TopiaEntityBinder<E> loador) throws DataSourceException { - if (Entities.isDataClass(klass)) { - // on verifie que l'on a le droit de lire la donnee - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data, no read credential"); - } - return new ArrayList<E>(); - } - } - - if (Entities.isReferentielClass(klass)) { - // on verifie que l'on a le droit de lire la donnee - if (!source.canReadReferentiel()) { - if (log.isDebugEnabled()) { - log.debug("Can not read referentiel, no read credential"); - } - return new ArrayList<E>(); - } - } - - List<E> result; - try { - - result = getList0(source, klass, predicate, loador); - - //TC-20100208 : on peut modifier la liste (pour supprimer par - // exemple les entites non active), on doit donc toujours travailler - // sur une copie de la liste - return new ArrayList<E>(result); - } catch (Exception e) { - throw new DataSourceException(e, "getList"); - } - } - - - public <E extends TopiaEntity> EntityMap findAllUsages(DataSource source, - E entity) throws DataSourceException { - - String txName = "findAllUsages"; - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<E> dao; - dao = source.getDAO(tx, entity); - - // always get a fresh version of object - entity = dao.findByTopiaId(entity.getTopiaId()); - EntityMap result; - result = new EntityMap(dao.findAllUsages(entity)); - if (decoratorService != null) { - // on charge les entites - for (Class<? extends TopiaEntity> aClass : result.keySet()) { - Decorator<? extends TopiaEntity> decorator = - decoratorService.getDecoratorByType(aClass); - for (TopiaEntity e : result.get(aClass)) { - decorator.toString(e); - } - } - } - return result; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public <E extends OpenableEntity & TopiaEntity> E getOpen(DataSource source, - Class<E> klass) throws DataSourceException { - - if (!source.canReadData()) { - if (log.isInfoEnabled()) { - log.info("Can not read data!"); - } - return null; - } - String txName = "getOpen"; - TopiaContext tx = beginTransaction(source, txName); - try { - E result = source.getOpen(tx, klass); - if (result != null && klass.equals(TripSeine.class)) { - ((TripSeine) result).getProgram(); - } - return result; - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<Program> getAllProgramStub(DataSource source) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return Collections.emptyList(); - } - - String txName = "getAllProgramStub"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - ProgramDAO dao = (ProgramDAO) source.getDAO(tx, Program.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - List<Program> result = dao.findAllStub(referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public Program getProgramStub(DataSource source, String programId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return null; - } - - String txName = "getProgramStub"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - ProgramDAO dao = (ProgramDAO) source.getDAO(tx, Program.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - Program result = dao.findStubByTopiaId(programId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<TripSeine> getTripSeineStubByProgram(DataSource source, String programId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return Collections.emptyList(); - } - - String txName = "getTripSeineStubByProgram"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - List<TripSeine> result = dao.findAllStubByProgramId(programId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public TripSeine getTripSeineStub(DataSource source, String tripId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return null; - } - - String txName = "getTripSeineStub"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - TripSeine result = dao.findStubByTopiaId(tripId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public List<Route> getRouteStubByTrip(DataSource source, String tripSeineId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return Collections.emptyList(); - } - - String txName = "getRouteStubByTrip"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - RouteDAO dao = (RouteDAO) source.getDAO(tx, Route.class); - List<Route> result = dao.findAllStubByTripId(tripSeineId); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public Route getRouteStub(DataSource source, String routeId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return null; - } - - String txName = "getRouteStub"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - RouteDAO dao = (RouteDAO) source.getDAO(tx, Route.class); - Route result = dao.findStubByTopiaId(routeId); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<ActivitySeine> getActivitySeineStubByRoute(DataSource source, String routeId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return Collections.emptyList(); - } - - String txName = "getActivitySeineStubByRoute"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - ActivitySeineDAO dao = (ActivitySeineDAO) source.getDAO(tx, ActivitySeine.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - List<ActivitySeine> result = dao.findAllStubByRouteId(routeId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public ActivitySeine getActivitySeineStub(DataSource source, String activityId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return null; - } - - String txName = "getActivitySeineStub"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - ActivitySeineDAO dao = (ActivitySeineDAO) source.getDAO(tx, ActivitySeine.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - ActivitySeine result = dao.findStubByTopiaId(activityId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<FloatingObject> getFloatinObjectStubByActivitySeine(DataSource source, String activitySeineId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return Collections.emptyList(); - } - - String txName = "getFloatinObjectStubByActivitySeine"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - FloatingObjectDAO dao = (FloatingObjectDAO) source.getDAO(tx, FloatingObject.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - List<FloatingObject> result = dao.findAllStubByActivityId(activitySeineId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public FloatingObject getFloatinObjectStub(DataSource source, String floatingObjectId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return null; - } - - String txName = "getFloatinObjectStub"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - FloatingObjectDAO dao = (FloatingObjectDAO) source.getDAO(tx, FloatingObject.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - FloatingObject result = dao.findStubByTopiaId(floatingObjectId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<TripLongline> getTripLonglineStubByProgram(DataSource source, String programId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return Collections.emptyList(); - } - - String txName = "getTripLonglineStubByProgram"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - List<TripLongline> result = dao.findAllStubByProgramId(programId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - - public TripLongline getTripLonglineStub(DataSource source, String tripId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return null; - } - - String txName = "getTripLonglineStub"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - TripLongline result = dao.findStubByTopiaId(tripId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - - public List<ActivityLongline> getActivityLonglineStubByTrip(DataSource source, String tripId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return Collections.emptyList(); - } - - String txName = "getActivityLonglineStubByTrip"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - ActivityLonglineDAO dao = (ActivityLonglineDAO) source.getDAO(tx, ActivityLongline.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - List<ActivityLongline> result = dao.findAllStubByTripId(tripId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public ActivityLongline getActivityLonglineStub(DataSource source, String activityId) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return null; - } - - String txName = "getActivityLonglineStub"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - ActivityLonglineDAO dao = (ActivityLonglineDAO) source.getDAO(tx, ActivityLongline.class); - ReferenceLocale referentielLocale = getDecoratorService().getReferentielLocale(); - ActivityLongline result = dao.findStubByTopiaId(activityId, referentielLocale); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public Ocean getTripOcean(DataSource source, String tripId) throws DataSourceException { - - String txName = "getTripOcean"; - TopiaContext tx = beginTransaction(source, txName); - try { - TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); - TripSeine result = dao.findByTopiaId(tripId); - return result.getOcean(); - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - /** - * Recherche d'un {@link LengthWeightParameter} à partir des paramètres donnés. - * <p/> - * La recherche peut ne peut être aussi exacte que les paramètres donnés : - * <p/> - * Dans le cas d'une espèce faune, si non trouvé alors on recherche sur son - * speciesGroup d'espèce. - * <p/> - * Si non trouvé pour l'océan donné (et que celui-ci est non null), alors on - * recherche avec un ocean vide. - * <p/> - * Si non trouvé sur le gender (et que le gender n'est pas indéterminé) , alors - * on recherche avec le gender indéterminé (gender=0). - * - * @param tx la transaction en cours d'utilisation - * @param species l'espèce sur lequel on recherche le paramétrage - * @param ocean l'ocean recherché (peut être null) - * @param sex le sexe recherché (on essayera sans sexe (sexe.code=0) si non trouvé) - * @param date le jour recherché - * @return le paramétrage adéquate - * @throws DataSourceException pour toute erreur - * @since 1.5 - */ - public <P extends LengthWeightParameter> P findLengthWeightParameter( - TopiaContext tx, - Species species, - Ocean ocean, - Sex sex, - Date date) throws DataSourceException { - - try { - - List<P> list = LengthWeightParemeterHelper.findBySpecies((TopiaContextImplementor) tx, species); - - if (CollectionUtils.isEmpty(list)) { - - // aucun parametrage pour le type donne - return null; - } - - // filtrage par ocean - List<P> filterByOcean = LengthWeightParemeterHelper.filterByOcean(list, ocean); - - if (CollectionUtils.isEmpty(filterByOcean) && ocean != null) { - - // filtre par ocean null - filterByOcean = LengthWeightParemeterHelper.filterByOcean(list, null); - } - list = filterByOcean; - - if (CollectionUtils.isEmpty(list)) { - - // pas d'ocean adequate - return null; - } - - // filtrage par sexe - List<P> filterBySexe = LengthWeightParemeterHelper.filterBySexe(list, sex); - - if (CollectionUtils.isEmpty(filterBySexe)) { - - Sex unkwonSex = getUnknownSex(tx); - - if (sex==null || unkwonSex.equals(sex)) { - - // filtrage par sexe indetermine - filterBySexe = LengthWeightParemeterHelper.filterBySexe(list, unkwonSex); - } - - list = filterBySexe; - - } - - if (CollectionUtils.isEmpty(list)) { - - // pas de sexe adequate - return null; - } - - // filtrage par startDate de validite - list = LengthWeightParemeterHelper.filterByDateDebutValidite(list, date); - - if (CollectionUtils.isEmpty(list)) { - - // pas de date de debut adequate - return null; - } - - // filtrage par endDate de validite - list = LengthWeightParemeterHelper.filterByDateFinValidite(list, date); - - if (CollectionUtils.isEmpty(list)) { - - // pas de date de fin adequate - return null; - } - - // au final il ne devrait en rester qu'un - - if (list.size() > 1) { - StringBuilder sb = new StringBuilder("Il existe plusieurs paramétrages possibles pour les données suivantes :"); - sb.append("\nEspece : "); - sb.append(getDecoratorService().decorate(species)); - sb.append("\nOcean : "); - sb.append(getDecoratorService().decorate(ocean)); - sb.append("\nSex : "); - sb.append(getDecoratorService().decorate(sex)); - sb.append("\nDate : ").append(date); - sb.append("\nParamétrages trouvés : "); - for (P p : list) { - sb.append("\n - ").append(getDecoratorService().decorate(p)); - } - throw new DataSourceException(sb.toString(), "findLengthWeightParameter"); - } - - P result = list.get(0); - if (log.isDebugEnabled()) { - StringBuilder sb = new StringBuilder("Paramétrage trouvé pour les données suivantes :"); - sb.append("\nEspece : "); - sb.append(getDecoratorService().decorate(species)); - sb.append("\nOcean : "); - sb.append(getDecoratorService().decorate(ocean)); - sb.append("\nSex : "); - sb.append(getDecoratorService().decorate(sex)); - sb.append("\nDate : ").append(date); - sb.append("\nParamétrage: ").append(getDecoratorService().decorate(result)); - log.debug(sb.toString()); - } - return result; - - } catch (Exception e) { - throw new DataSourceException(e, "findLengthWeightParameter"); - } - } - - protected Sex getUnknownSex(TopiaContext tx) { - return ObserveDAOHelper.getSexDAO(tx).findByCode("0"); - } - - public int getOpenablePosition(DataSource source, - String containerId, - String childId) throws DataSourceException { - if (childId.startsWith(TripSeine.class.getName())) { - return getTripSeinePosition(source, containerId, childId); - } - if (childId.startsWith(TripLongline.class.getName())) { - return getTripLonglinePosition(source, containerId, childId); - } - if (childId.startsWith(Route.class.getName())) { - return getRoutePosition(source, containerId, childId); - } - if (childId.startsWith(ActivitySeine.class.getName())) { - return getActivitySeinePosition(source, containerId, childId); - } - if (childId.startsWith(ActivityLongline.class.getName())) { - return getActivityLonglinePosition(source, containerId, childId); - } - throw new IllegalStateException("Can not come here!"); - } - - protected int getTripSeinePosition(DataSource source, - String programId, - String tripId) throws DataSourceException { - - String txName = "getTripSeinePosition [" + tripId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); - int pos = dao.findPositionByProgramId(programId, tripId); - return pos; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - protected int getTripLonglinePosition(DataSource source, - String programId, - String tripId) throws DataSourceException { - - String txName = "getTripLonglinePosition [" + tripId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); - int pos = dao.findPositionByProgramId(programId, tripId); - return pos; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - protected int getRoutePosition(DataSource source, - String tripId, - String routeId) throws DataSourceException { - - String txName = "getRoutePosition [" + tripId + "/" + routeId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - TripSeine maree = source.getDAO(tx, TripSeine.class).findByTopiaId(tripId); - Route route = maree.getRouteByTopiaId(routeId); - List<Route> routes = maree.getRoute(); - Routes.sort(routes); - return routes.indexOf(route); - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - protected int getActivitySeinePosition(DataSource source, - String routeId, - String activityId) throws DataSourceException { - - String txName = "getActivitySeinePosition [" + routeId + "/" + activityId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - Route route = source.getDAO(tx, Route.class).findByTopiaId(routeId); - ActivitySeine activitySeine = route.getActivitySeineByTopiaId(activityId); - List<ActivitySeine> activitySeines = route.getActivitySeine(); - ActivitySeines.sort(activitySeines); - return activitySeines.indexOf(activitySeine); - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - protected int getActivityLonglinePosition(DataSource source, - String tripId, - String activityId) throws DataSourceException { - - String txName = "getActivityLonglinePosition [" + tripId + "/" + activityId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - TripLongline trip = source.getDAO(tx, TripLongline.class).findByTopiaId(tripId); - ActivityLongline activity = trip.getActivityLonglineByTopiaId(activityId); - List<ActivityLongline> activities = trip.getActivityLongline(); - ActivityLonglines.sort(activities); - return activities.indexOf(activity); - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public String getTargetSampleId(DataSource source, - String setId, - boolean discarded) throws DataSourceException { - - String txName = "getTargetSampleId [" + setId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); - SetSeine set = dao.findByTopiaId(setId); - List<TargetSample> list = set.getTargetSample(); - if (list == null || list.isEmpty()) { - return null; - } - for (TargetSample targetSample : list) { - if (discarded) { - if (targetSample.getDiscarded() != null && - targetSample.getDiscarded()) { - return targetSample.getTopiaId(); - } - } else if (targetSample.getDiscarded() == null || - !targetSample.getDiscarded()) { - return targetSample.getTopiaId(); - } - } - return null; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public String getNonTargetSampleId(DataSource source, - String setId) throws DataSourceException { - - String txName = "getNonTargetSampleId [" + setId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); - SetSeine set = dao.findByTopiaId(setId); - List<NonTargetSample> list = set.getNonTargetSample(); - if (list == null || list.isEmpty()) { - return null; - } - return list.get(0).getTopiaId(); - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public List<Species> getAvailableEspeceForTargetSample(DataSource source, - String setId, - boolean discarded) throws DataSourceException { - - String txName = "getAvailableEspeceForTargetSample [" + setId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - List<Species> speciess = new ArrayList<Species>(); - - TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); - SetSeine set = dao.findByTopiaId(setId); - - // on recupere la liste des species thon utilisees dans le rejet - Collection<TargetCatch> discardeds = set.getTargetCatch(); - - // on filtre sur les speciess monté sur le pont et rejetée - - if (discardeds != null) { - for (TargetCatch discardedt : discardeds) { - boolean keep; - - if (discarded) { - - // on ne conserve que les speciess des discardeds montees sur le pont et discardedes - keep = discardedt.isDiscarded() && discardedt.getBroughtOnDeck(); - - } else { - - // on ne conserve que les species des discardeds - keep = !discardedt.isDiscarded(); - } - - if (keep && - !speciess.contains(discardedt.getWeightCategory().getSpecies())) { - speciess.add(discardedt.getWeightCategory().getSpecies()); - } - } - } - return speciess; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public List<Species> getAvailableEspeceForNonTargetSample(DataSource source, - String setId) throws DataSourceException { - - String txName = "getAvailableEspeceForNonTargetSample [" + setId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - List<Species> speciess = new ArrayList<Species>(); - - TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); - SetSeine set = dao.findByTopiaId(setId); - - // on recupere la liste des species faune utilisees dans le rejet - Collection<NonTargetCatch> discardeds = set.getNonTargetCatch(); - - if (discardeds != null) { - for (NonTargetCatch discarded : discardeds) { - // on retient toute les speciess (capturées ou rejetées) - if (!speciess.contains(discarded.getSpecies())) { - speciess.add(discarded.getSpecies()); - } - } - } - - return speciess; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<Section> getSections(DataSource source, String setLonglineId) throws DataSourceException { - String txName = "getSections [" + setLonglineId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - TopiaDAO<Section> dao = source.getDAO(tx, Section.class); - - List<Section> sections = dao.findAllByProperties(Section.PROPERTY_SET_LONGLINE + "." + Section.TOPIA_ID, setLonglineId); - - if (!sections.isEmpty()) { - - Decorator<Section> sectionDecorator = getDecoratorService().getDecoratorByType(Section.class); - Decorator<Basket> basketDecorator = getDecoratorService().getDecoratorByType(Basket.class); - Decorator<Branchline> branchlineDecorator = getDecoratorService().getDecoratorByType(Branchline.class); - - for (Section section : sections) { - - sectionDecorator.toString(section); - - if (!section.isBasketEmpty()) { - - for (Basket basket : section.getBasket()) { - - basketDecorator.toString(basket); - - if (!basket.isBranchlineEmpty()) { - - for (Branchline branchline : basket.getBranchline()) { - - branchlineDecorator.toString(branchline); - - } - } - - } - } - } - } - - return sections; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - - - public List<Species> loadDecoratedSpecies(DataSource source, String speciesListCode) throws DataSourceException { - String txName = "loadDecoratedSpecies [" + speciesListCode + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - List<Species> speciess = new ArrayList<Species>(); - - SpeciesListDAO dao = (SpeciesListDAO) source.getDAO(tx, SpeciesList.class); - SpeciesList speciesList = dao.findByTopiaId(speciesListCode); - - speciess.addAll(speciesList.getSpecies()); - - Decorator<Species> decorator = getDecoratorService().getDecoratorByType(Species.class); - - for (Species species : speciess) { - decorator.toString(species); - } - - return speciess; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public java.util.Set<String> getSpeciesListSpeciesIds(DataSource source, String speciesListId) throws DataSourceException { - String txName = "getSpeciesListSpeciesIds [" + speciesListId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - - SpeciesListDAO dao = (SpeciesListDAO) source.getDAO(tx, SpeciesList.class); - SpeciesList speciesList = dao.findByTopiaId(speciesListId); - - java.util.Set<String> ids = - Sets.newHashSet( - TopiaEntityHelper.getTopiaIdList( - speciesList.getSpecies())); - - return ids; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public boolean canUseNonTargetSample(DataSource source, - String setId) throws DataSourceException { - - String txName = "canUseNonTargetSample [" + setId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); - SetSeine set = dao.findByTopiaId(setId); - - return set.canUseNonTargetSample(); - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public boolean canUseTargetSample(DataSource source, - String setId, - boolean discarded) throws DataSourceException { - - String txName = "canUseTargetSample [" + setId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - - TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); - SetSeine set = dao.findByTopiaId(setId); - - return set.canUseTargetSample(discarded); - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public void getObsoleteEspeceForNonTargetSample(DataSource source, - String setId, - List<Species> speciessUsed, - Collection<Species> speciessToDelete, - List<NonTargetLength> tailleToDelete) throws DataSourceException { - - String txName = "getObsoleteEspeceForNonTargetSample [" + setId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); - SetSeine set = dao.findByTopiaId(setId); - - - if (set.isNonTargetSampleEmpty()) { - return; - } - - NonTargetSample echantillon = set.getNonTargetSample().get(0); - - if (echantillon.isNonTargetLengthEmpty()) { - return; - } - - for (NonTargetLength taille : echantillon.getNonTargetLength()) { - Species tailleEspece = taille.getSpecies(); - if (!speciessUsed.contains(tailleEspece)) { - // l'species n'existe plus dans les rejet faune, - // on doit le supprimer - tailleToDelete.add(taille); - speciessToDelete.add(tailleEspece); - if (log.isDebugEnabled()) { - log.debug("remove obsolote echantillon " + taille + - " for species " + tailleEspece); - } - } - } - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - - - public void getObsoleteEspeceForTargetSample(DataSource source, - String setId, - Collection<Species> speciessUsed, - Collection<Species> speciessToDelete, - List<TargetLength> tailleToDelete, boolean discarded) throws DataSourceException { - - String txName = "getObsoleteEspeceForTargetSample [" + setId + "]"; - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<SetSeine> dao = source.getDAO(tx, SetSeine.class); - SetSeine set = dao.findByTopiaId(setId); - - if (set.isTargetSampleEmpty()) { - return; - } - - TargetSample echantillon = set.getTargetSample(discarded); - - if (echantillon == null || echantillon.isTargetLengthEmpty()) { - return; - } - - for (TargetLength taille : echantillon.getTargetLength()) { - Species tailleEspece = taille.getSpecies(); - if (!speciessUsed.contains(tailleEspece)) { - // l'species n'existe plus dans les rejet faune, - // on doit le supprimer - tailleToDelete.add(taille); - speciessToDelete.add(tailleEspece); - if (log.isDebugEnabled()) { - log.debug("remove obsolote echantillon " + taille + - " for species " + tailleEspece); - } - } - } - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<Program> getPossibleProgramsForTrip(DataSource source, String tripId) throws DataSourceException { - - final GearType gearType; - - String txName = "getPossibleProgramsForTrip : " + tripId; - TopiaContext tx = beginTransaction(source, txName); - try { - - Trip trip; - - if (tripId.contains(TripSeine.class.getSimpleName())) { - trip = source.getDAO(tx, TripSeine.class).findByTopiaId(tripId); - } else { - trip = source.getDAO(tx, TripLongline.class).findByTopiaId(tripId); - } - - gearType = trip.getProgram().getGearType(); - - ProgramDAO dao = (ProgramDAO) source.getDAO(tx, Program.class); - - List<Program> programs = dao.findAllByGearType(gearType); - - for (Program program : programs) { - decoratorService.decorate(program); - } - - return programs; - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - - public void moveTripToProgram(DataSource source, String tripId, String programId) throws DataSourceException { - - String txName = "moveTripToProgram : " + tripId + " :: " + programId; - TopiaContext tx = beginTransaction(source, txName); - try { - - Trip trip; - - if (tripId.contains(TripSeine.class.getSimpleName())) { - trip = source.getDAO(tx, TripSeine.class).findByTopiaId(tripId); - } else { - trip = source.getDAO(tx, TripLongline.class).findByTopiaId(tripId); - } - - ProgramDAO dao = (ProgramDAO) source.getDAO(tx, Program.class); - - Program program = dao.findByTopiaId(programId); - - trip.setProgram(program); - - tx.commitTransaction(); - - if (trip.isOpen()) { - - // refresh the dataContext - dataContext.setOpenProgramId(programId); - - } - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - - public List<SizeMeasure> getCatchLonglineSizeMeasures(DataSource source, CatchLongline bean, final TopiaEntityBinder<SizeMeasure> binder) throws DataSourceException { - - String txName = "getSections : " + bean.getTopiaId(); - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<CatchLongline> dao = source.getDAO(tx, CatchLongline.class); - CatchLongline catchLongline = dao.findByTopiaId(bean.getTopiaId()); - List<SizeMeasure> result = new ArrayList<SizeMeasure>(); - for (SizeMeasure sizeSource : catchLongline.getSizeMeasure()) { - SizeMeasure target = new SizeMeasureImpl(); - binder.load(sizeSource, target, true); - result.add(target); - } - return result; - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<WeightMeasure> getCatchLonglineWeightMeasures(DataSource source, CatchLongline bean, final TopiaEntityBinder<WeightMeasure> binder) throws DataSourceException { - - String txName = "getSections : " + bean.getTopiaId(); - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<CatchLongline> dao = source.getDAO(tx, CatchLongline.class); - CatchLongline catchLongline = dao.findByTopiaId(bean.getTopiaId()); - List<WeightMeasure> result = new ArrayList<WeightMeasure>(); - for (WeightMeasure weightSource : catchLongline.getWeightMeasure()) { - WeightMeasure target = new WeightMeasureImpl(); - binder.load(weightSource, target, true); - result.add(target); - } - return result; - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<GearUseFeaturesMeasurementSeine> getDefaultGearUseFeaturesMeasurementSeine(DataSource source, String gearId) throws DataSourceException { - - String txName = "getDefaultGearUseFeaturesMeasurementSeine : " + gearId; - TopiaContext tx = beginTransaction(source, txName); - try { - - TopiaDAO<Gear> gearDao = source.getDAO(tx, Gear.class); - Gear gear = gearDao.findByTopiaId(gearId); - - Collection<GearCaracteristic> gearCaracteristic = gear.getGearCaracteristic(); - List<GearUseFeaturesMeasurementSeine> result = new ArrayList<GearUseFeaturesMeasurementSeine>(); - for (GearCaracteristic caracteristic : gearCaracteristic) { - GearUseFeaturesMeasurementSeine target = new GearUseFeaturesMeasurementSeineImpl(); - target.setGearCaracteristic(caracteristic); - result.add(target); - } - - return result; - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<GearUseFeaturesMeasurementSeine> getGearUseFeaturesMeasurementSeine(DataSource source, GearUseFeaturesSeine bean, final TopiaEntityBinder<GearUseFeaturesMeasurementSeine> binder) throws DataSourceException { - - String txName = "getGearUseFeaturesMeasurementSeine : " + bean.getTopiaId(); - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<GearUseFeaturesSeine> dao = source.getDAO(tx, GearUseFeaturesSeine.class); - GearUseFeaturesSeine gearUseFeaturesSeine = dao.findByTopiaId(bean.getTopiaId()); - List<GearUseFeaturesMeasurementSeine> result = new ArrayList<GearUseFeaturesMeasurementSeine>(); - for (GearUseFeaturesMeasurementSeine measurementSource : gearUseFeaturesSeine.getGearUseFeaturesMeasurement()) { - GearUseFeaturesMeasurementSeine target = new GearUseFeaturesMeasurementSeineImpl(); - measurementSource.getGearCaracteristic().getGearCaracteristicType(); - binder.load(measurementSource, target, true); - result.add(target); - } - return result; - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<GearUseFeaturesMeasurementLongline> getDefaultGearUseFeaturesMeasurementLongline(DataSource source, String gearId) throws DataSourceException { - - String txName = "getDefaultGearUseFeaturesMeasurementLongline : " + gearId; - TopiaContext tx = beginTransaction(source, txName); - try { - - TopiaDAO<Gear> gearDao = source.getDAO(tx, Gear.class); - Gear gear = gearDao.findByTopiaId(gearId); - - Collection<GearCaracteristic> gearCaracteristic = gear.getGearCaracteristic(); - List<GearUseFeaturesMeasurementLongline> result = new ArrayList<GearUseFeaturesMeasurementLongline>(); - for (GearCaracteristic caracteristic : gearCaracteristic) { - GearUseFeaturesMeasurementLongline target = new GearUseFeaturesMeasurementLonglineImpl(); - target.setGearCaracteristic(caracteristic); - result.add(target); - } - - return result; - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<GearUseFeaturesMeasurementLongline> getGearUseFeaturesMeasurementLongline(DataSource source, GearUseFeaturesLongline bean, final TopiaEntityBinder<GearUseFeaturesMeasurementLongline> binder) throws DataSourceException { - - String txName = "getGearUseFeaturesMeasurementLongline : " + bean.getTopiaId(); - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<GearUseFeaturesLongline> dao = source.getDAO(tx, GearUseFeaturesLongline.class); - GearUseFeaturesLongline gearUseFeaturesLongline = dao.findByTopiaId(bean.getTopiaId()); - List<GearUseFeaturesMeasurementLongline> result = new ArrayList<GearUseFeaturesMeasurementLongline>(); - for (GearUseFeaturesMeasurementLongline measurementSource : gearUseFeaturesLongline.getGearUseFeaturesMeasurement()) { - GearUseFeaturesMeasurementLongline target = new GearUseFeaturesMeasurementLonglineImpl(); - measurementSource.getGearCaracteristic().getGearCaracteristicType(); - binder.load(measurementSource, target, true); - result.add(target); - } - return result; - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public <E extends TopiaEntity> List<String> getEntityIds(DataSource source, - Class<E> refClass) - throws DataSourceException { - - String txName = "getEntityIds : " + refClass; - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaDAO<E> dao = source.getDAO(tx, refClass); - List<String> result = dao.findAllIds(); - return result; - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - public List<TripMapPoint> loadTripMapActivityPoints(DataSource source, String id) throws DataSourceException { - if (!source.canReadData()) { - if (log.isDebugEnabled()) { - log.debug("Can not read data!"); - } - return null; - } - - String txName = "loadTrip"; - TopiaContext tx = beginTransaction(source, txName); - - List<TripMapPoint> tripMapPoints; - - try { - if (Entities.isSeineId(id)) { - TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); - - tripMapPoints = dao.extractTripMapActivityPoints(id); - - } else if (Entities.isLonglineId(id)) { - - TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); - - tripMapPoints = dao.extractTripMapActivityPoints(id); - - } else { - throw new ObserveTechnicalException(String.format("id '%s' is not seine id or longe line id", id)); - } - - } catch (TopiaException e) { - throw new DataSourceException(e, txName); - } finally{ - closeTransaction(source, tx, txName); - } - return tripMapPoints; - } - - - // ------------------------------------------------------------------------ - // -- Méthodes de chargement de données - // ------------------------------------------------------------------------ - - - public TopiaEntity loadEntity(DataSource source, - String id, - boolean decorate) throws DataSourceException { - - String txName = "loadEntity : " + id; - TopiaContext tx = beginTransaction(source, txName); - try { - TopiaEntity result = tx.findByTopiaId(id); - //FIXME Find a better way to do this... - if (result instanceof ActivitySeine) { - - // on charge toujours sa calée - ((ActivitySeine) result).getSetSeine(); - } - if (result instanceof ActivityLongline) { - - // on charge toujours sa calée - ((ActivityLongline) result).getSetLongline(); - } - if (decorate) { - Decorator<TopiaEntity> decorator = - getDecoratorService().getDecorator(result); - if (decorator == null) { - if (log.isWarnEnabled()) { - log.warn("Decorateur non trouvé pour l'objet " + result); - } - } else { - decorator.toString(result); - } - } - return result; - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public <E extends TopiaEntity> void loadEditEntity(DataSource source, - String entityId, - TopiaExecutor<E> updator) throws DataSourceException { - - String txName = "loadEditEntity :: " + entityId; - TopiaContext tx = beginTransaction(source, txName); - try { - E bean = source.findByTopiaId(tx, entityId); - updator.execute(tx, bean); - } catch (Exception e) { - throw new DataSourceException("Can not load edit entity " + entityId, e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public <E extends TopiaEntity> List<E> loadEntityAssociation(DataSource source, - Class<E> entityClass, - String property, - String parentId) throws DataSourceException { - - TopiaContext tx = beginTransaction(source, "loadEntitiesWithProperties"); - try { - - Class<TopiaEntity> parentclass = TopiaId.getClassName(parentId); - - TopiaDAO<?> parentDao = source.getDAO(tx, parentclass); - - // get parent entity - TopiaEntity parent = parentDao.findByTopiaId(parentId); - - // get parent operator - EntityOperator<TopiaEntity> operator = - ObserveDAOHelper.getOperator(parentclass); - - // get property from parent - List<E> result = (List<E>) operator.get(property, parent); - - DecoratorService decoratorService = getDecoratorService(); - - if (decoratorService != null) { - - // chargement des rendus - Decorator<E> decorator = - decoratorService.getDecoratorByType(entityClass); - for (E e : result) { - decorator.toString(e); - } - } - return result; - } catch (TopiaException e) { - throw new DataSourceException( - "Can not obtain topiaentity " + - parentId, e, "loadEntitiesWithProperties"); - } finally { - closeTransaction(source, tx, "loadEntitiesWithProperties"); - } - } - - public <E extends TopiaEntity, C extends TopiaEntity> void copyAssociation(Class<E> entityType, - Class<C> childEntityType, - String propertyName, - E source, - E target, - TopiaContext targetTx) { - - EntityOperator<E> operator = ObserveDAOHelper.getOperator(entityType); - - Collection<C> sourceList = (Collection<C>) operator.get(propertyName, source); - - TopiaDAO<C> dao = ObserveDAOHelper.getDAO(targetTx, childEntityType); - - List<C> targetList = Lists.newArrayListWithCapacity(sourceList.size()); - for (C sourceC : sourceList) { - - C targetC = dao.findByTopiaId(sourceC.getTopiaId()); - targetList.add(targetC); - } - operator.set(propertyName, target, targetList); - - } - - public String getSensorUsedDataFilename(DataSource source, SensorUsed sensorUSed) throws DataSourceException { - - String txName = "getSensorUsedDataFilename"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - TripLongline tripLongline = source.getOpen(tx, TripLongline.class); - - StringBuilder filenameBuilder = new StringBuilder("sensorData"); - String code = tripLongline.getVessel().getCode(); - filenameBuilder.append("-").append(code); - - Date startDate = tripLongline.getStartDate(); - filenameBuilder.append("-").append(new SimpleDateFormat("yyyy.MM.dd").format(startDate)); - - SensorType sensorType = sensorUSed.getSensorType(); - if (sensorType != null && sensorType.getCode() != null) { - filenameBuilder.append("-").append(sensorType.getCode()); - } - - String sensorSerialNo = sensorUSed.getSensorSerialNo(); - if (sensorSerialNo != null) { - filenameBuilder.append("-").append(sensorSerialNo); - } - filenameBuilder.append("-").append(sensorUSed.getDataFilename()); - - String filename = filenameBuilder.toString(); - return filename; - - } finally { - - closeTransaction(source, tx, txName); - - } - - } - - public String getTdrDataFilename(DataSource source, Tdr tdr) throws DataSourceException { - - String txName = "getTdrDataFilename"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - TripLongline tripLongline = source.getOpen(tx, TripLongline.class); - - StringBuilder filenameBuilder = new StringBuilder("tdr"); - String code = tripLongline.getVessel().getCode(); - filenameBuilder.append("-").append(code); - - Date startDate = tripLongline.getStartDate(); - filenameBuilder.append("-").append(new SimpleDateFormat("yyyy.MM.dd").format(startDate)); - - String homeId = tdr.getHomeId(); - if (homeId != null) { - filenameBuilder.append("-").append(homeId); - } - - String serialNo = tdr.getSerialNo(); - if (serialNo != null) { - filenameBuilder.append("-").append(serialNo); - } - filenameBuilder.append("-").append(tdr.getDataFilename()); - - String filename = filenameBuilder.toString(); - return filename; - - } finally { - - closeTransaction(source, tx, txName); - - } - - } - - public <E extends TopiaEntity> List<E> loadDecoratedEntities(DataSource source, - Class<E> entityClass) throws DataSourceException { - - String txName = "loadEntities :: " + entityClass.getName(); - TopiaContext tx = beginTransaction(source, txName); - Decorator<E> decorator = getDecoratorService().getDecoratorByType(entityClass); - try { - List<E> result = - source.loadDecoratedEntities(tx, entityClass, decorator); - return result; - } finally { - closeTransaction(source, tx, txName); - } - } - - - public <E extends TopiaEntity> List<E> loadDecoratedEntities(DataSource source, - Class<E> entityClass, - TopiaExecutor<E> loador) throws DataSourceException { - - String txName = "loadDecoratedEntities :: " + entityClass.getName(); - TopiaContext tx = beginTransaction(source, txName); - Decorator<E> decorator = getDecoratorService().getDecoratorByType(entityClass); - try { - List<E> result = - source.loadDecoratedEntities(tx, entityClass, decorator); - - if (CollectionUtils.isNotEmpty(result)) { - for (E e : result) { - try { - loador.execute(tx, e); - } catch (TopiaException e1) { - throw new DataSourceException( - "Can not obtain load entity " + e.getTopiaId(), e1, txName); - } - } - } - return result; - } finally { - closeTransaction(source, tx, txName); - } - } - - // ------------------------------------------------------------------------ - // -- Méthodes de création - mise à jour - suppression de données - // ------------------------------------------------------------------------ - - - public <E extends TopiaEntity, P extends TopiaEntity> E preCreate(DataSource source, - String parentBeanId, - E bean, - Loador<E> binder, - TopiaExecutor2<P, E> creator) throws DataSourceException { - - String txName = "preCreate"; - TopiaContext tx = beginTransaction(source, txName); - try { - P parentBean = null; - - if (parentBeanId != null) { - - // il y a un parent a recuperer - try { - parentBean = source.<P>findByTopiaId(tx, parentBeanId); - } catch (TopiaException e) { - - // pas possible de recuperer le parent - throw new DataSourceException(e, txName); - } - - checkNotNullAndExistingEntity(PARENT_BEAN, parentBean); - } - - // on charge le bean - binder.load(null, bean, true); - - checkNotNullAndNoneExistingEntity(BEAN, bean); - - E result; - if (creator == null) { - result = bean; - } else { - try { - result = creator.execute(tx, parentBean, bean); - } catch (TopiaException ex) { - throw new DataSourceException(ex, txName); - } - } - return result; - } finally { - closeTransaction(source, tx, txName); - } - } - - - public <E extends TopiaEntity, P extends TopiaEntity> E create(DataSource source, - String parentBeanId, - E bean, - Loador<E> binder, - TopiaExecutor2<P, E> creator) throws DataSourceException { - - checkNotNullAndNoneExistingEntity("bean", bean); - - String txName = "create"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - P parentBean = null; - - if (parentBeanId != null) { - - // il y a un parent a recuperer - try { - parentBean = source.<P>findByTopiaId(tx, parentBeanId); - } catch (TopiaException e) { - - // pas possible de recuperer le parent - throw new DataSourceException(e, txName); - } - - checkNotNullAndExistingEntity(PARENT_BEAN, parentBean); - } - - E beanToSave = creator.execute(tx, parentBean, bean); - - if (binder != null) { - binder.load(bean, beanToSave, false); - } - - if (parentBean == null) { - - // sauvegarde de l'entité autolastNamee - TopiaDAO<E> dao = source.getDAO(tx, beanToSave); - dao.update(beanToSave); - } else { - - // sauvegarde du père de l'entité - TopiaDAO<P> dao = source.getDAO(tx, parentBean); - dao.update(parentBean); - } - - commitTransaction(source, tx, txName); - return beanToSave; - } catch (Exception e) { - rollbackTransaction(source, tx, txName); - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public <E extends TopiaEntity, P extends TopiaEntity> E update(DataSource source, - String parentBeanId, - E bean, - TopiaExecutor2<P, E> updator) throws DataSourceException { - - checkNotNullAndExistingEntity("bean", bean); - - String txName = "update"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - P parentBean = null; - - if (parentBeanId != null) { - - // il y a un parent a recuperer - try { - parentBean = source.<P>findByTopiaId(tx, parentBeanId); - } catch (TopiaException e) { - - // pas possible de recuperer le parent - throw new DataSourceException(e, txName); - } - - checkNotNullAndExistingEntity(PARENT_BEAN, parentBean); - } - - E beanToSave; - - try { - beanToSave = source.<E>findByTopiaId(tx, bean.getTopiaId()); - } catch (TopiaException e) { - - // pas possible de recuperer le parent - throw new DataSourceException(e, txName); - } - - checkNotNullAndExistingEntity(BEAN, beanToSave); - - beanToSave = updator.execute(tx, parentBean, beanToSave); - - if (parentBean == null) { - - // sauvegarde de l'entité autolastNamee - TopiaDAO<E> dao = source.getDAO(tx, beanToSave); - dao.update(beanToSave); - } else { - - // sauvegarde du père de l'entité - TopiaDAO<P> dao = source.getDAO(tx, parentBean); - dao.update(parentBean); - } - - commitTransaction(source, tx, txName); - return beanToSave; - } catch (Exception e) { - rollbackTransaction(source, tx, txName); - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - public void updateOpenProperty(DataSource source, - String id, - boolean newValue) throws DataSourceException { - - if (!source.canWriteData()) { - - // pas autorisé à écrire des données observer - return; - } - - String txName = "updateOpenProperty :: " + id + " - " + newValue; - TopiaContext tx = null; - try { - tx = beginTransaction(source, txName); - OpenableEntity beanToSave = source.findByTopiaId(tx, id); - beanToSave.setOpen(newValue); - commitTransaction(source, tx, txName); - } catch (TopiaException e) { - throw new DataSourceException( - "Can not update open state for " + id, e, txName); - } finally { - closeTransaction(source, tx, txName); - } - } - - - @SuppressWarnings({"unchecked"}) - public <P extends TopiaEntity, E extends TopiaEntity> void delete(DataSource source, - String parentBeanId, - E bean, - TopiaExecutor2<P, E> deletor) throws DataSourceException { - - checkNotNullAndExistingEntity("bean", bean); - - String txName = "delete"; - TopiaContext tx = beginTransaction(source, txName); - - try { - - P parentBean = null; - - TopiaDAO<TopiaEntity> parentDao = null; - - if (parentBeanId != null) { - parentBean = (P) tx.findByTopiaId(parentBeanId); - - checkNotNullAndExistingEntity("parentBean", parentBean); - - parentDao = source.getDAO(tx, (TopiaEntity) parentBean); - } - - E beanToDelete = (E) tx.findByTopiaId(bean.getTopiaId()); - - deletor.execute(tx, parentBean, beanToDelete); - - if (parentBeanId != null) { - - parentDao.update(parentBean); - } - - commitTransaction(source, tx, txName); - } catch (Exception e) { - rollbackTransaction(source, tx, "create"); - if (e instanceof DataSourceException) { - throw (DataSourceException) e; - } - throw new DataSourceException(e, txName); - } - } - - - public void close() { - decoratorService = null; - dataContext = null; - } - - - public <E extends TopiaEntity> void checkNotNullAndNoneExistingEntity(String variableName, E entity) { - TopiaEntityHelper.checkNotNullAndNoneExistingEntity(variableName, entity); - } - - - public <E extends TopiaEntity> void checkNotNullAndExistingEntity(String variableName, E entity) { - TopiaEntityHelper.checkNotNullAndExistingEntity(variableName, entity); - } - - - public DiffState.DiffStateMap buildReferentielDifferentiel(final DataSource srcService, - final DataSource dstService, - final SendMessageAble messanger) - throws DataSourceException { - try { - final DiffState.DiffStateMap result = DiffState.newMap(); - ReferenceEntities.walk(new ReferenceEntities.ReferentielWalker() { - - - public <E extends TopiaEntity> void walk( - Class<E> contractClass) throws Exception { - - String s = t(DecoratorService.getEntityLabel(contractClass)); - String message = - t("observe.service.build.synchro.referentiel", s); - if (messanger != null) { - messanger.sendMessage(message); - } - if (log.isInfoEnabled()) { - log.info(message); - } - List<E> list = getList(srcService, contractClass); - List<E> list2 = getList(dstService, contractClass); - DiffState.DiffStateMap tmp; - // recuperation du differentiel pour le type d'entitétmp = - tmp = TopiaEntityHelper.buildDifferentiel(list, list2); - // ajout au resultat - DiffState.addAll(result, tmp); - // on nettoie - DiffState.clear(tmp); - } - }); - DiffState.removeEmptyStates(result); - return result; - } catch (DataSourceException ex) { - throw ex; - } catch (Exception ex) { - throw new DataSourceException(ex, "buildReferentielDifferentiel"); - } - } - - protected <E extends TopiaEntity> List<E> getList0(DataSource source, - Class<E> klass, - Predicate<E> predicate, - TopiaEntityBinder<E> loador) throws Exception { - - TopiaContext tx = beginTransaction(source, "getList0 : " + klass); - try { - TopiaDAO<E> dao = source.getDAO(tx, klass); - List<E> result = dao.findAll(); - - if (predicate != null) { - - // use a filter - result = Lists.newArrayList(Iterables.filter(result, predicate)); - - } - if (loador != null) { - for (E e : result) { - loador.obtainProperties(e); - } - } - return result; - } finally { - closeTransaction(source, tx, "getList0 : " + klass); - } - } - - // ------------------------------------------------------------------------ - // -- Property change support - // ------------------------------------------------------------------------ - - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListeners() { - for (PropertyChangeListener listener : pcs.getPropertyChangeListeners()) { - removePropertyChangeListener(listener); - } - } - - public <E extends TopiaEntity> void addReferentielPropertyChangeListener(Class<E> entitClass, PropertyChangeListener listener) { - ObserveEntityEnum constant = ObserveEntityEnum.valueOf(entitClass); - String propertyName = getReferentielPropertyName(constant); - log.info(propertyName + " :" + listener); - addPropertyChangeListener(propertyName, listener); - } - - public <E extends TopiaEntity> void addDataPropertyChangeListener(Class<E> entitClass, PropertyChangeListener listener) { - ObserveEntityEnum constant = ObserveEntityEnum.valueOf(entitClass); - String propertyName = getDataPropertyName(constant); - addPropertyChangeListener(propertyName, listener); - } - - public void removeReferentielPropertyChangeListeners() { - for (ObserveEntityEnum constant : Entities.REFERENCE_ENTITIES) { - String propertyName = getReferentielPropertyName(constant); - PropertyChangeListener[] changeListeners = pcs.getPropertyChangeListeners(propertyName); - if (log.isDebugEnabled()) { - log.debug(propertyName + " :" + changeListeners.length); - } - for (PropertyChangeListener listener : - changeListeners) { - if (log.isDebugEnabled()) { - log.debug(propertyName + " :" + listener); - } - removePropertyChangeListener(propertyName, listener); - } - } - } - - protected String getReferentielPropertyName(ObserveEntityEnum constant) { - return DataSource.REFERENTIEL_PROPERTY_KEY + "#" + constant.name(); - } - - protected String getDataPropertyName(ObserveEntityEnum constant) { - return DataSource.DATA_PROPERTY_KEY + "#" + constant.name(); - } - - protected void firePropertyChangedEvent(PropertyChangeEvent event, - String message, - PropertyChangeListener... listeners) { - for (PropertyChangeListener listener : listeners) { - if (log.isInfoEnabled()) { - log.info(message + ", notifiy listener " + listener); - } - listener.propertyChange(event); - } - } - - protected PropertyChangeListener[] getPropertyChangeListener(String propertyName) { - List<PropertyChangeListener> result = new ArrayList<PropertyChangeListener>(); - for (PropertyChangeListener listener : pcs.getPropertyChangeListeners()) { - if (listener instanceof PropertyChangeListenerProxy) { - PropertyChangeListenerProxy proxy = - (PropertyChangeListenerProxy) listener; - if (!propertyName.equals(proxy.getPropertyName())) { - continue; - } - } - result.add(listener); - } - return result.toArray(new PropertyChangeListener[result.size()]); - } - - protected void fireOpenChanged(DataSource source) { - - String propertyName = DataSource.OPEN_PROPERTY_KEY; - - if (log.isInfoEnabled()) { - log.info("Open context changed, will notifiy listeners [" + propertyName + "]..."); - } - - // obtain all opens ids - try { - - String[] ids = getOpenIds(source); - - String message = Arrays.toString(ids); - - PropertyChangeListener[] listeners = getPropertyChangeListener(propertyName); - if (listeners.length == 0) { - // pas de listener, on ne fait rien - - - if (log.isInfoEnabled()) { - log.info("Open context " + message + ", No listener, skip"); - } - return; - } - - PropertyChangeEvent event = new PropertyChangeEvent(this, propertyName, null, ids); - firePropertyChangedEvent(event, "Open context " + message + " changed", listeners); - - } catch (DataSourceException e) { - if (log.isErrorEnabled()) { - log.error("Could not fire open changed", e); - } - } - } - - protected void fireReferentielChanged(DataSource source, ObserveEntityEnum... types) { - for (ObserveEntityEnum constant : types) { - try { - String propertyName = getReferentielPropertyName(constant); - if (log.isInfoEnabled()) { - log.info("Referentiel [" + constant + "] changed, will notifiy listeners [" + propertyName + "]..."); - } - - PropertyChangeListener[] listeners = getPropertyChangeListener(propertyName); - if (listeners.length == 0) { - // pas de listener, on ne fait rien - - if (log.isInfoEnabled()) { - log.info("Referentiel [" + constant + "] No listener, skip"); - } - return; - } - - List<? extends TopiaEntity> entities = getList(source, constant.getContract()); - if (log.isInfoEnabled()) { - log.info("Referentiel [" + constant + "] new size " + entities.size()); - } - - PropertyChangeEvent event = new PropertyChangeEvent(this, propertyName, null, entities); - firePropertyChangedEvent(event, "Referentiel [" + constant + "] changed", listeners); - } catch (DataSourceException e) { - if (log.isErrorEnabled()) { - log.error("Could not fire referentiel [" + constant + "] changed"); - } - } - } - } - - protected void fireDataChanged(DataSource source, TopiaEntity... types) { - for (TopiaEntity entity : types) { - - ObserveEntityEnum constant = - ObserveEntityEnum.valueOf(entity); - - // une entite donnee observer a ete modifiee, supprimer ou cree - // on notifie tous les écouteurs des données observer - - String propertyName = getDataPropertyName(constant); - if (log.isInfoEnabled()) { - log.info("Data [" + entity.getTopiaId() + "] changed, will notifiy listeners [" + propertyName + "]..."); - } - - PropertyChangeListener[] listeners = getPropertyChangeListener(propertyName); - if (listeners.length == 0) { - // pas de listener, on ne fait rien - - if (log.isDebugEnabled()) { - log.debug("Data [" + entity.getTopiaId() + "] No listener, skip"); - } - return; - } - - PropertyChangeEvent event = new PropertyChangeEvent(this, propertyName, null, entity); - firePropertyChangedEvent(event, "Data [" + entity + "] changed", listeners); - } - } - - public void deleteTrip(DataSource source, String tripId) throws DataSourceException { - - String txName = "deleteTrip"; - TopiaContext tx = beginTransaction(source, txName); - try { - - if (Entities.isSeineId(tripId)) { - - TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); - TripSeine result = dao.findByTopiaId(tripId); - dao.delete(result); - - } else { - - TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); - TripLongline result = dao.findByTopiaId(tripId); - dao.delete(result); - - } - - skipTransactionListener = true; - try { - - commitTransaction(source, tx, txName); - - } finally { - skipTransactionListener = false; - } - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - - public boolean updateEndDate(DataSource source, String tripId) throws DataSourceException { - - boolean wasUpdated; - - String txName = "updateEndDate"; - TopiaContext tx = beginTransaction(source, txName); - try { - - if (Entities.isSeineId(tripId)) { - - TripSeineDAO dao = (TripSeineDAO) source.getDAO(tx, TripSeine.class); - TripSeine trip = dao.findByTopiaId(tripId); - wasUpdated = dao.updateEndDate(trip); - - } else { - - TripLonglineDAO dao = (TripLonglineDAO) source.getDAO(tx, TripLongline.class); - TripLongline trip = dao.findByTopiaId(tripId); - wasUpdated = dao.updateEndDate(trip); - - } - - if (wasUpdated) { - commitTransaction(source, tx, txName); - } - - return wasUpdated; - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - - public void updateDayDate(DataSource source, String routeId) throws DataSourceException { - - String txName = "updateDayDate"; - TopiaContext tx = beginTransaction(source, txName); - try { - - RouteDAO dao = (RouteDAO) source.getDAO(tx, Route.class); - dao.updateActivitiesDate(routeId); - commitTransaction(source, tx, txName); - - } catch (Exception e) { - throw new DataSourceException(e, txName); - } finally { - closeTransaction(source, tx, txName); - } - - } - -} diff --git a/observe-business/src/main/java/fr/ird/observe/DecoratorService.java b/observe-business/src/main/java/fr/ird/observe/DecoratorService.java deleted file mode 100644 index 5979b6f..0000000 --- a/observe-business/src/main/java/fr/ird/observe/DecoratorService.java +++ /dev/null @@ -1,611 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import fr.ird.observe.decorator.LengthWeightParameterDecorator; -import fr.ird.observe.decorator.NonTargetCatchDecorator; -import fr.ird.observe.decorator.NonTargetLengthDecorator; -import fr.ird.observe.decorator.ObjectObservedSpeciesDecorator; -import fr.ird.observe.decorator.ReferenceDecorator; -import fr.ird.observe.decorator.SpeciesDecorator; -import fr.ird.observe.decorator.TripLonglineDecorator; -import fr.ird.observe.decorator.TripSeineDecorator; -import fr.ird.observe.entities.constants.ReferenceLocale; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.Basket; -import fr.ird.observe.entities.longline.Branchline; -import fr.ird.observe.entities.longline.CatchLongline; -import fr.ird.observe.entities.longline.Section; -import fr.ird.observe.entities.longline.SectionTemplate; -import fr.ird.observe.entities.longline.SetLongline; -import fr.ird.observe.entities.longline.Tdr; -import fr.ird.observe.entities.referentiel.Country; -import fr.ird.observe.entities.referentiel.FpaZone; -import fr.ird.observe.entities.referentiel.Gear; -import fr.ird.observe.entities.referentiel.GearCaracteristic; -import fr.ird.observe.entities.referentiel.GearCaracteristicType; -import fr.ird.observe.entities.referentiel.Harbour; -import fr.ird.observe.entities.referentiel.Ocean; -import fr.ird.observe.entities.referentiel.Organism; -import fr.ird.observe.entities.referentiel.Person; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.referentiel.ReferenceEntity; -import fr.ird.observe.entities.referentiel.Sex; -import fr.ird.observe.entities.referentiel.SpeciesGroup; -import fr.ird.observe.entities.referentiel.SpeciesList; -import fr.ird.observe.entities.referentiel.Vessel; -import fr.ird.observe.entities.referentiel.VesselSizeCategory; -import fr.ird.observe.entities.referentiel.VesselType; -import fr.ird.observe.entities.referentiel.longline.BaitHaulingStatus; -import fr.ird.observe.entities.referentiel.longline.BaitSettingStatus; -import fr.ird.observe.entities.referentiel.longline.BaitType; -import fr.ird.observe.entities.referentiel.longline.CatchFateLongline; -import fr.ird.observe.entities.referentiel.longline.EncounterType; -import fr.ird.observe.entities.referentiel.longline.Healthness; -import fr.ird.observe.entities.referentiel.longline.HookPosition; -import fr.ird.observe.entities.referentiel.longline.HookSize; -import fr.ird.observe.entities.referentiel.longline.HookType; -import fr.ird.observe.entities.referentiel.longline.ItemHorizontalPosition; -import fr.ird.observe.entities.referentiel.longline.ItemVerticalPosition; -import fr.ird.observe.entities.referentiel.longline.LightsticksColor; -import fr.ird.observe.entities.referentiel.longline.LightsticksType; -import fr.ird.observe.entities.referentiel.longline.LineType; -import fr.ird.observe.entities.referentiel.longline.MaturityStatus; -import fr.ird.observe.entities.referentiel.longline.MitigationType; -import fr.ird.observe.entities.referentiel.longline.SensorBrand; -import fr.ird.observe.entities.referentiel.longline.SensorDataFormat; -import fr.ird.observe.entities.referentiel.longline.SensorType; -import fr.ird.observe.entities.referentiel.longline.SettingShape; -import fr.ird.observe.entities.referentiel.longline.SizeMeasureType; -import fr.ird.observe.entities.referentiel.longline.StomacFullness; -import fr.ird.observe.entities.referentiel.longline.TripType; -import fr.ird.observe.entities.referentiel.longline.VesselActivityLongline; -import fr.ird.observe.entities.referentiel.longline.WeightMeasureType; -import fr.ird.observe.entities.referentiel.seine.DetectionMode; -import fr.ird.observe.entities.referentiel.seine.ObjectFate; -import fr.ird.observe.entities.referentiel.seine.ObjectOperation; -import fr.ird.observe.entities.referentiel.seine.ObjectType; -import fr.ird.observe.entities.referentiel.seine.ObservedSystem; -import fr.ird.observe.entities.referentiel.seine.ReasonForDiscard; -import fr.ird.observe.entities.referentiel.seine.ReasonForNoFishing; -import fr.ird.observe.entities.referentiel.seine.ReasonForNullSet; -import fr.ird.observe.entities.referentiel.seine.SpeciesFate; -import fr.ird.observe.entities.referentiel.seine.SpeciesStatus; -import fr.ird.observe.entities.referentiel.seine.SurroundingActivity; -import fr.ird.observe.entities.referentiel.seine.TransmittingBuoyOperation; -import fr.ird.observe.entities.referentiel.seine.TransmittingBuoyType; -import fr.ird.observe.entities.referentiel.seine.VesselActivitySeine; -import fr.ird.observe.entities.referentiel.seine.WeightCategory; -import fr.ird.observe.entities.referentiel.seine.Wind; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.ObjectSchoolEstimate; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SchoolEstimate; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TargetCatch; -import fr.ird.observe.entities.seine.TargetLength; -import fr.ird.observe.entities.seine.TransmittingBuoy; -import fr.ird.observe.business.gps.GPSPoint; -import fr.ird.observe.business.gps.GPSPointInterval; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.decorator.DecoratorProvider; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.TopiaEntityRef; - -import java.beans.Introspector; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.nuiton.i18n.I18n.l; -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - - -/** - * Le service de décoration. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class DecoratorService extends DecoratorProvider { - - /** Logger */ - private static final Log log = LogFactory.getLog(DecoratorService.class); - - /** Le pattern pour utiliser les clef i18n generees dans les entites */ - protected static final Pattern LABEL_PATTERN = Pattern.compile("observe\\.common\\.(.+)"); - - public static final String HAULING_IDENTIFIER = "haulingIdentifier"; - - public static final String OBSERVE_COMMON_PREFIX = "observe.common."; - - /** la locale du referentiel. */ - protected ReferenceLocale referentielLocale; - - public DecoratorService(ReferenceLocale referentielLocale) { - this.referentielLocale = referentielLocale; - loadDecorators(); - } - - public ReferenceLocale getReferentielLocale() { - return referentielLocale; - } - - public void setReferentielLocale(ReferenceLocale referentielLocale) { - this.referentielLocale = referentielLocale; - } - - public Matcher getPropertyMatch(String regex) { - return LABEL_PATTERN.matcher(regex); - } - - @SuppressWarnings({"unchecked"}) - public static String getEntityLabel(Class entityClass) { - return getEntityLabel(OBSERVE_COMMON_PREFIX, entityClass); - } - - public static String getEntityLabel(String prefix, Class entityClass) { - if (!TopiaEntity.class.isAssignableFrom(entityClass)) { - throw new IllegalArgumentException( - entityClass + " is not a TopiaEntity"); - } - entityClass = ObserveDAOHelper.getContractClass(entityClass); - return getPropertyLabel(prefix, entityClass.getSimpleName()); - } - - - public static String getPropertyLabel(String propertyName) { - String type = getPropertyLabel(OBSERVE_COMMON_PREFIX, propertyName); - return type; - } - - public static String getPropertyLabel(String prefix, String propertyName) { - String type = prefix + Introspector.decapitalize(propertyName); - return type; - } - - public Class<?>[] sortTypes(Class<?>... types) { - List<Class<?>> list = Arrays.asList(types); - final Map<Class<?>, String> cache = new HashMap<Class<?>, String>(); - - Comparator<Class<?>> result = new Comparator<Class<?>>() { - - @Override - public int compare(Class<?> o1, Class<?> o2) { - String s1 = getValue(o1); - String s2 = getValue(o2); - return s1.compareTo(s2); - } - - String getValue(Class<?> klass) { - String result = cache.get(klass); - if (result == null) { - // calcul de la valeur - result = t(getEntityLabel(klass)); - cache.put(klass, result); - } - return result; - } - }; - Collections.sort(list, result); - cache.clear(); - return list.toArray(new Class<?>[list.size()]); - } - - public String decorate(Object o) { - Decorator<Object> decorator = getDecorator(o); - String result = ""; - if (decorator != null) { - result = decorator.toString(o); - } - return result; - } - - public String decorate(String context, Object o) { - Decorator<Object> decorator = getDecorator(o, context); - String result = ""; - if (decorator != null) { - result = decorator.toString(o); - } - return result; - } - - static { - // pour avoir les traduction sur le lastName de la propriété - n("observe.common.vesselActivitySeine/label1"); - n("observe.common.vesselActivitySeine/label2"); - n("observe.common.vesselActivitySeine/label3"); - n("observe.common.vesselActivitySeine/label4"); - n("observe.common.vesselActivitySeine/label5"); - n("observe.common.vesselActivitySeine/label6"); - n("observe.common.vesselActivitySeine/label7"); - n("observe.common.vesselActivitySeine/label8"); - - n("observe.common.vessel/label1"); - n("observe.common.vessel/label2"); - n("observe.common.vessel/label3"); - n("observe.common.vessel/label4"); - n("observe.common.vessel/label5"); - n("observe.common.vessel/label6"); - n("observe.common.vessel/label7"); - n("observe.common.vessel/label8"); - - n("observe.common.ocean/label1"); - n("observe.common.ocean/label2"); - n("observe.common.ocean/label3"); - n("observe.common.ocean/label4"); - n("observe.common.ocean/label5"); - n("observe.common.ocean/label6"); - n("observe.common.ocean/label7"); - n("observe.common.ocean/label8"); - - n("observe.common.species/scientificLabel"); - n("observe.common.observerLabel"); - - - n("observe.common.targetSample"); - n("observe.common.targetLength"); - n("observe.common.nonTargetSample"); - n("observe.common.nonTargetLength"); - n("observe.common.nonTargetCatch"); - n("observe.common.setSeine"); - n("observe.common.targetCatch"); - n("observe.common.transmittingBuoy"); - n("observe.common.objectObservedSpecies"); - n("observe.common.schoolEstimate"); - n("observe.common.objectSchoolEstimate"); - n("observe.common.floatingObject"); - n("observe.common.activitySeine"); - n("observe.common.route"); - n("observe.common.tripSeine"); - - n("observe.common.activityLongline"); - n("observe.common.baitsComposition"); - n("observe.common.basket"); - n("observe.common.branchline"); - n("observe.common.branchlinesComposition"); - n("observe.common.catchLongline"); - n("observe.common.encounter"); - n("observe.common.setLongline"); - n("observe.common.time"); - n("observe.common.floatlinesComposition"); - n("observe.common.hooksComposition"); - n("observe.common.section"); - n("observe.common.sensorUsed"); - n("observe.common.sizeMeasure"); - n("observe.common.tdr"); - n("observe.common.tdrRecord"); - n("observe.common.tripLongline"); - n("observe.common.weightMeasure"); - n("observe.common.gearUseFeaturesSeine"); - n("observe.common.gearUseFeaturesLongline"); - - n("observe.common.vesselSizeCategory"); - n("observe.common.harbour"); - n("observe.common.country"); - n("observe.common.vesselType"); - n("observe.common.vessel"); - n("observe.common.speciesGroup"); - n("observe.common.species"); - n("observe.common.sex"); - n("observe.common.fpaZone"); - n("observe.common.speciesList"); - n("observe.common.person"); - n("observe.common.ocean"); - n("observe.common.organism"); - n("observe.common.lengthWeightParameter"); - n("observe.common.program"); - - n("observe.common.vesselActivitySeine"); - n("observe.common.surroundingActivity"); - n("observe.common.reasonForNullSet"); - n("observe.common.reasonForNoFishing"); - n("observe.common.speciesFate"); - n("observe.common.objectFate"); - n("observe.common.weightCategory"); - n("observe.common.detectionMode"); - n("observe.common.transmittingBuoyOperation"); - n("observe.common.objectOperation"); - n("observe.common.reasonForDiscard"); - n("observe.common.speciesStatus"); - n("observe.common.observedSystem"); - n("observe.common.transmittingBuoyType"); - n("observe.common.objectType"); - n("observe.common.wind"); - - n("observe.common.baitHaulingStatus"); - n("observe.common.baitSettingStatus"); - n("observe.common.baitType"); - n("observe.common.catchFateLongline"); - n("observe.common.encounterType"); - n("observe.common.healthness"); - n("observe.common.hookPosition"); - n("observe.common.hookSize"); - n("observe.common.hookType"); - n("observe.common.itemVerticalPosition"); - n("observe.common.itemHorizontalPosition"); - n("observe.common.lightsticksColor"); - n("observe.common.lightsticksType"); - n("observe.common.lineType"); - n("observe.common.maturityStatus"); - n("observe.common.mitigationType"); - n("observe.common.sensorBrand"); - n("observe.common.sensorDataFormat"); - n("observe.common.sensorPosition"); - n("observe.common.sensorType"); - n("observe.common.settingShape"); - n("observe.common.sizeMeasureType"); - n("observe.common.stomacFullness"); - n("observe.common.tripType"); - n("observe.common.vesselActivityLongline"); - n("observe.common.weightMeasureType"); - n("observe.common.id"); - n("observe.common.floatlineLengths"); - n("observe.common.locode"); - n("observe.common.name"); - n("observe.common.gearCaracteristicType"); - n("observe.common.gearCaracteristic"); - n("observe.common.gear"); - n("observe.common.gender"); - - n("observe.common.floatline1Length"); - n("observe.common.floatline2Length"); - n("observe.common.branchlineLength"); - n("observe.common.tracelineLength"); - - } - - @Override - protected void loadDecorators() { - if (referentielLocale == null) { - // on n'enregistre pas les décorateur tant que la locale n'est pas - // positionnée - return; - } - - Locale locale = referentielLocale.getLocale(); - - String libelle = referentielLocale.getLibelle(); - registerJXPathDecorator(Program.class, - t("observe.common.program") + - " ${" + libelle + "}$s"); - registerJXPathDecorator(Route.class, - "${date}$td/%1$tm/%1$tY"); - registerMultiJXPathDecorator( - ActivitySeine.class, - "${time}$tH:%1$tM##${vesselActivitySeine/" + libelle + "}$s", - "##", " - "); - registerMultiJXPathDecorator( - ActivityLongline.class, - "${timeStamp}$td/%1$tm/%1$tY %1$tH:%1$tM##${vesselActivityLongline/" + libelle + "}$s", - "##", " - "); - registerMultiJXPathDecorator(Person.class, "${lastName}$s##${firstName}$s", "##", " "); - registerDefaultReferenceEntityDecorator(Sex.class, libelle); - //FIXME Use startDate - endDate - registerDefaultReferenceEntityDecorator(FpaZone.class, libelle); - registerDefaultReferenceEntityDecorator(Ocean.class, libelle); - registerDefaultReferenceEntityDecorator(DetectionMode.class, libelle); - registerDefaultReferenceEntityDecorator(Vessel.class, libelle); - registerDefaultReferenceEntityDecorator(Country.class, libelle); - registerReferenceEntityDecorator(VesselSizeCategory.class, "${code}$s##${gaugeLabel}$s##${capacityLabel}$s"); - registerDefaultReferenceEntityDecorator(VesselType.class, libelle); - registerDefaultReferenceEntityDecorator(VesselActivitySeine.class, libelle); - registerDefaultReferenceEntityDecorator(SurroundingActivity.class, libelle); - registerDefaultReferenceEntityDecorator(ObservedSystem.class, libelle); - registerReferenceEntityDecorator(Wind.class, "${code}$s##${" + libelle + "}$s##${speedRange}$s"); - registerMultiJXPathDecorator( - FloatingObject.class, - "DCP ${objectType/" + libelle + "}$s", "##", " - "); - //FIXME Remove this - registerJXPathDecorator(SetSeine.class, t("observe.common.setSeine")); - //FIXME Remove this - registerJXPathDecorator(SetLongline.class, t("observe.common.setLongline")); - registerDefaultReferenceEntityDecorator(ObjectFate.class, libelle); - registerDefaultReferenceEntityDecorator(Organism.class, libelle); - registerDefaultReferenceEntityDecorator(ObjectType.class, libelle); - registerDefaultReferenceEntityDecorator(ObjectOperation.class, libelle); - registerDefaultReferenceEntityDecorator(SpeciesStatus.class, libelle); - registerDefaultReferenceEntityDecorator(TransmittingBuoyType.class, libelle); - registerDefaultReferenceEntityDecorator(TransmittingBuoyOperation.class, libelle); - registerDefaultReferenceEntityDecorator(ReasonForNullSet.class, libelle); - registerDefaultReferenceEntityDecorator(ReasonForNoFishing.class, libelle); - registerDefaultReferenceEntityDecorator(WeightCategory.class, libelle); - registerDefaultReferenceEntityDecorator(ReasonForDiscard.class, libelle); - registerDefaultReferenceEntityDecorator(SpeciesFate.class, libelle); - registerDefaultReferenceEntityDecorator(SpeciesGroup.class, libelle); - registerDefaultReferenceEntityDecorator(SpeciesList.class, libelle); - - registerDefaultReferenceEntityDecorator(BaitHaulingStatus.class, libelle); - registerDefaultReferenceEntityDecorator(BaitSettingStatus.class, libelle); - registerDefaultReferenceEntityDecorator(BaitType.class, libelle); - registerDefaultReferenceEntityDecorator(CatchFateLongline.class, libelle); - registerDefaultReferenceEntityDecorator(EncounterType.class, libelle); - registerDefaultReferenceEntityDecorator(Healthness.class, libelle); - registerDefaultReferenceEntityDecorator(HookPosition.class, libelle); - registerDefaultReferenceEntityDecorator(HookSize.class, libelle); - registerDefaultReferenceEntityDecorator(HookType.class, libelle); - registerDefaultReferenceEntityDecorator(ItemVerticalPosition.class, libelle); - registerDefaultReferenceEntityDecorator(ItemHorizontalPosition.class, libelle); - registerDefaultReferenceEntityDecorator(LightsticksColor.class, libelle); - registerDefaultReferenceEntityDecorator(LightsticksType.class, libelle); - registerDefaultReferenceEntityDecorator(LineType.class, libelle); - registerDefaultReferenceEntityDecorator(MaturityStatus.class, libelle); - registerDefaultReferenceEntityDecorator(MitigationType.class, libelle); - registerReferenceEntityDecorator(SensorBrand.class, "${code}$s##${brandName}$s"); - registerDefaultReferenceEntityDecorator(SensorDataFormat.class, libelle); - registerDefaultReferenceEntityDecorator(SensorType.class, libelle); - registerDefaultReferenceEntityDecorator(SettingShape.class, libelle); - registerDefaultReferenceEntityDecorator(SizeMeasureType.class, libelle); - registerDefaultReferenceEntityDecorator(StomacFullness.class, libelle); - registerDefaultReferenceEntityDecorator(TripType.class, libelle); - registerDefaultReferenceEntityDecorator(VesselActivityLongline.class, libelle); - registerDefaultReferenceEntityDecorator(WeightMeasureType.class, libelle); - registerDefaultReferenceEntityDecorator(GearCaracteristicType.class, libelle); - registerDefaultReferenceEntityDecorator(GearCaracteristic.class, libelle); - registerDefaultReferenceEntityDecorator(Gear.class, libelle); - - registerReferenceEntityDecorator(Harbour.class, "${code}$s##${name}$s##${locode}$s"); - - registerMultiJXPathDecorator( - ObjectSchoolEstimate.class, - "${species/scientificLabel}$s##${weight}$d", "##", - " - "); - registerMultiJXPathDecorator( - SchoolEstimate.class, - "${species/scientificLabel}$s##${weight}$d##${meanWeight}$d", "##", " - "); - registerMultiJXPathDecorator( - TargetCatch.class, - "${weightCategory/species/scientificLabel}$s##${weightCategory/" + libelle + "}$s##${weight}$f", "##", " - "); - registerMultiJXPathDecorator( - TargetLength.class, - "${species/scientificLabel}$s##${length}$f##${count}$d", "##", " - "); - - registerMultiJXPathDecorator( - TransmittingBuoy.class, - "${transmittingBuoyType/" + libelle + "}$s##${transmittingBuoyOperation/" + libelle + "}$s##${code}$s", "##", - " - "); - - String settingIdentifier = l(locale, "observe.common.settingIdentifier"); - String haulingIdentifier = l(locale, "observe.common.haulingIdentifier"); - - registerMultiJXPathDecorator( - Section.class, - " ${settingIdentifier}$s (" + settingIdentifier + ")##${haulingIdentifier}$s (" + haulingIdentifier + ")", "##", " - "); - - registerMultiJXPathDecorator( - Basket.class, - " ${settingIdentifier}$s (" + settingIdentifier + ")##${haulingIdentifier}$s (" + haulingIdentifier + ")", "##", " - "); - - registerMultiJXPathDecorator( - Branchline.class, - " ${settingIdentifier}$s (" + settingIdentifier + ")##${haulingIdentifier}$s (" + haulingIdentifier + ")", "##", " - "); - - registerJXPathDecorator(Section.class, HAULING_IDENTIFIER, "${haulingIdentifier}$s"); - registerJXPathDecorator(Basket.class, HAULING_IDENTIFIER, "${haulingIdentifier}$s"); - registerJXPathDecorator(Branchline.class, HAULING_IDENTIFIER, "${haulingIdentifier}$s"); - - // TripSeine decorator - registerDecorator(new TripSeineDecorator(libelle)); - - // TripLongline decorator - registerDecorator(new TripLonglineDecorator(libelle)); - - String oldCode = l(locale, "observe.common.oldCode3L"); - // Species decorator - registerDecorator(new SpeciesDecorator(libelle, oldCode)); - - // ObjectObservedSpecies decorator - registerDecorator(new ObjectObservedSpeciesDecorator(libelle)); - - // NonTargetCatch decorator - registerDecorator(new NonTargetCatchDecorator(libelle)); - - // NonTargetLength decorator - registerDecorator(new NonTargetLengthDecorator(libelle)); - - // LengthWeightParameter decorator - registerDecorator(new LengthWeightParameterDecorator(libelle)); - - registerDecorator(new TopiaEntityRefDecorator()); - - // gps decorators - registerJXPathDecorator(ActivitySeine.class, - "activity-gps", - t("observe.common.gps.activity")); - registerJXPathDecorator(GPSPoint.class, - "gpsPoint-gps", - t("observe.common.gps.gpsPoint")); - registerJXPathDecorator(GPSPointInterval.class, - "gpsPointInterval-gps", - t("observe.common.gps.gpsPointInterval")); - - registerMultiJXPathDecorator(GPSPoint.class, - "${time}$td/%1$tm/%1$tY %1$tH:%1$tM##${latitude}$s##${longitude}$s", - "##", " "); - - registerMultiJXPathDecorator(SectionTemplate.class, "${id}$s##${floatlineLengths}$s", "##", " "); - - registerJXPathDecorator(CatchLongline.class, "${homeId}$s"); - registerJXPathDecorator(Tdr.class, "${homeId}$s"); - } - - - protected <T extends ReferenceEntity> void registerDefaultReferenceEntityDecorator(Class<T> referenceType, String libelle) { - registerReferenceEntityDecorator(referenceType, "${code}$s##${" + libelle + "}$s"); - } - - protected <T extends ReferenceEntity> void registerReferenceEntityDecorator(Class<T> referenceType, String expression) { - registerDecorator(new ReferenceDecorator<T>(referenceType, expression)); - } - - public class TopiaEntityRefDecorator extends Decorator<TopiaEntityRef> { - - private static final long serialVersionUID = 1L; - - public TopiaEntityRefDecorator() throws NullPointerException { - super(TopiaEntityRef.class); - } - - @Override - public String toString(Object bean) { - if (bean == null) { - return ""; - } - String message; - try { - TopiaEntityRef ref = (TopiaEntityRef) bean; - - TopiaEntity invoker = ref.getInvoker(); - if (invoker == null) { - invoker = ref.getRef(); - } - String invokerProperty = - t(getPropertyLabel( - ref.getInvokerProperty())); - String type = t(getEntityLabel(invoker.getClass())); - Decorator<?> decorator = - getDecoratorByType(invoker.getClass()); - if (invokerProperty == null) { - message = t("observe.synchro.obsolete.entity.label", type, decorator.toString(invoker)); - } else { - message = t("observe.synchro.obsolete.entity.ref", type, decorator.toString(invoker), invokerProperty); - } - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error(e); - } - message = ""; - } - return message; - } - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/IObserveConfig.java b/observe-business/src/main/java/fr/ird/observe/IObserveConfig.java deleted file mode 100644 index e60c742..0000000 --- a/observe-business/src/main/java/fr/ird/observe/IObserveConfig.java +++ /dev/null @@ -1,412 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.db.impl.PGDataSourceConfig; -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import org.nuiton.version.Version; - -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.Locale; - -/** - * Contrat de la configuration d'Observe. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public interface IObserveConfig { - /** - * le fichier de configuration de l'application avec les informations sur le - * projet (version, license,...) et la configuration des ui (icons, ...) - */ - String APPLICATION_PROPERTIES = "/observe.properties"; - - /** le lastName du repertoire ou sont les donnees de l'application */ - String USER_DIRECTORY_FILENAME = ".observe"; - - /** le pattern du fichier de sauvegarde d'une base locale */ - String BACKUP_DB_PATTERN = "obstuna-local-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; - - /** le pattern du fichier de sauvegarde d'une base access importée */ - String ACCESS_DB_PATTERN = "import-access-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; - - /** le pattern du fichier de rapport après validation */ - String REPORT_PATTERN = "report-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; - - /** - * La version de l'application. - */ - String APPLICATION_VERSION = "application.version"; - - /** - * La version du modèle de la persistence - */ - String DB_VERSION = AbstractDataSourceMigration.DB_VERSION; - - String VERSION = "version"; - - String PROPERTY_DEFAULT_DB_MODE = "defaultDbMode"; - - String PROPERTY_DEFAULT_CREATION_MODE = "defaultCreationMode"; - - String PROPERTY_SPECIES_LIST_SEINE_TARGET_CATCH_ID = "speciesListSeineTargetCatchId"; - - String PROPERTY_SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID = "speciesListSeineSchoolEstimateId"; - - String PROPERTY_SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID = "speciesListSeineObjectSchoolEstimateId"; - - String PROPERTY_SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID = "speciesListSeineNonTargetCatchId"; - - String PROPERTY_SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID = "speciesListSeineObjectObservedSpeciesId"; - - String PROPERTY_SPECIES_LIST_LONGLINE_CATCH_ID = "speciesListLonglineCatchId"; - - String PROPERTY_SPECIES_LIST_LONGLINE_ENCOUNTER_ID = "speciesListLonglineEncounterId"; - - String PROPERTY_SPECIES_LIST_LONGLINE_DEPREDATOR_ID = "speciesListLonglineDepredatorId"; - - String PROPERTY_VERSION = "version"; - - String PROPERTY_DB_VERSION = "dbVersion"; - - String PROPERTY_AUTO_POPUP_NUMBER_EDITOR = "autoPopupNumberEditor"; - - String PROPERTY_SHOW_NUMBER_EDITOR_BUTTON = "showNumberEditorButton"; - - String PROPERTY_SHOW_DATE_TIME_EDITOR_SLIDER= "showTimeEditorSlider"; - - String PROPERTY_LOCAL_STORAGE_EXIST = "localStorageExist"; - - String PROPERTY_INITIAL_DUMP_EXIST = "initialDumpExist"; - - String PROPERTY_MAIN_STORAGE_OPENED = "mainStorageOpened"; - - String PROPERTY_STORE_REMOTE_STORAGE = "storeRemoteStorage"; - - String PROPERTY_DEFAULT_GPS_MAX_DELAY = "defaultGpsMaxDelay"; - - String PROPERTY_DEFAULT_GPS_MAX_SPEED = "defaultGpsMaxSpeed"; - - String PROPERTY_CHANGE_SYNCHRO_SRC = "changeSynchroSrc"; - - String PROPERTY_NON_TARGET_OBSERVATION = "nonTargetObservation"; - - String PROPERTY_TARGET_DISCARDS_OBSERVATION = "targetDiscardsObservation"; - - String PROPERTY_SAMPLES_OBSERVATION = "samplesObservation"; - - String PROPERTY_OBJECTS_OBSERVATION = "objectsObservation"; - - String PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION = "detailledActivitiesObservation"; - - String PROPERTY_MAMMALS_OBSERVATION = "mammalsObservation"; - - String PROPERTY_BIRDS_OBSERVATION = "birdsObservation"; - - String PROPERTY_BAIT_OBSERVATION = "baitObservation"; - - String PROPERTY_RESOURCES_DIRECTORY = "resourcesDirectory"; - - String PROPERTY_LOCALE = "locale"; - - String PROPERTY_DB_LOCALE = "dbLocale"; - - String PROPERTY_CAN_MIGRATE_OBSTUNA = "canMigrateObstuna"; - - String PROPERTY_CAN_MIGRATE_H2 = "canMigrateH2"; - - String PROPERTY_MAIN_STORAGE_OPENED_LOCAL = "mainStorageOpenedLocal"; - - String PROPERTY_COPYRIGHT_TEXT = "copyrightText"; - - String PROPERTY_FULL_SCREEN = "fullScreen"; - - String PROPERTY_LOCAL_DBDIRECTORY = "localDBDirectory"; - - String PROPERTY_I18N_DIRECTORY = "i18nDirectory"; - - String PROPERTY_INITIAL_DB_DUMP = "initialDbDump"; - - String PROPERTY_BACKUP_DIRECTORY = "backupDirectory"; - - String PROPERTY_REPORT_DIRECTORY = "reportDirectory"; - - String PROPERTY_MAP_DIRECTORY = "mapDirectory"; - - String PROPERTY_TMP_DIRECTORY = "tmpDirectory"; - - String PROPERTY_DISPLAY_MAIN_UI = "displayMainUI"; - - String PROPERTY_CAN_USE_UI = "canUseUI"; - - String PROPERTY_ADJUSTING = "adjusting"; - - String PROPERTY_H2_LOGIN = "h2Login"; - - String PROPERTY_H2_PASSWORD = "h2Password"; - - String PROPERTY_OBSTUNA_URL = "obstunaUrl"; - - String PROPERTY_OBSTUNA_LOGIN = "obstunaLogin"; - - String PROPERTY_OBSTUNA_PASSWORD = "obstunaPassword"; - - String PROPERTY_OBSTUNA_USE_SSL = "obstunaUseSsl"; - - String PROPERTY_LOAD_LOCAL_STORAGE = "loadLocalStorage"; - - String PROPERTY_SHOW_MIGRATION_PROGRESSION = "showMigrationProgression"; - - String PROPERTY_SHOW_MIGRATION_SQL = "showMigrationSql"; - - String PROPERTY_VALIDATION_REPORT_DIRECTORY = "validationReportDirectory"; - - String PROPERTY_SHOW_SQL = "showSql"; - - String PROPERTY_H2_SERVER_PORT = "h2ServerPort"; - - String PROPERTY_DEV_MODE = "devMode"; - - boolean isDevMode(); - - Version getVersion(); - - Version getDbVersion(); - - boolean isAutoPopupNumberEditor(); - - boolean isShowNumberEditorButton(); - - boolean isShowTimeEditorSlider(); - - boolean isLocalStorageExist(); - - boolean isInitialDumpExist(); - - boolean isMainStorageOpened(); - - boolean isStoreRemoteStorage(); - - int getDefaultGpsMaxDelay(); - - float getDefaultGpsMaxSpeed(); - - boolean isChangeSynchroSrc(); - - int getNonTargetObservation(); - - int getTargetDiscardsObservation(); - - int getSamplesObservation(); - - int getObjectsObservation(); - - int getDetailledActivitiesObservation(); - - int getMammalsObservation(); - - int getBirdsObservation(); - - int getBaitObservation(); - - File getResourcesDirectory(); - - Locale getLocale(); - - Locale getDbLocale(); - - boolean isCanMigrateObstuna(); - - boolean isCanMigrateH2(); - - Boolean getMainStorageOpenedLocal(); - - String getCopyrightText(); - - boolean isFullScreen(); - - File getLocalDBDirectory(); - - File getI18nDirectory(); - - File getInitialDbDump(); - - File getBackupDirectory(); - - File getReportDirectory(); - - File getTmpDirectory(); - - File getLogConfigurationFile(); - - boolean isDisplayMainUI(); - - boolean isCanUseUI(); - - boolean isAdjusting(); - - String getH2Login(); - - char[] getH2Password(); - - String getObstunaUrl(); - - String getObstunaLogin(); - - char[] getObstunaPassword(); - - boolean isObstunaUseSsl(); - - boolean isLoadLocalStorage(); - - boolean isShowMigrationProgression(); - - boolean isShowMigrationSql(); - - File getValidationReportDirectory(); - - boolean isShowSql(); - - int getH2ServerPort(); - - void setResourcesDirectory(File newValue); - - DbMode getDefaultDbMode(); - - CreationMode getDefaultCreationMode(); - - void saveForUser(String... excludeKeys); - - void fromStorageConfig(H2DataSourceConfig config); - - void fromStorageConfig(PGDataSourceConfig config); - - H2DataSourceConfig toH2StorageConfig(String label); - - PGDataSourceConfig toPostgresStorageConfig(String label); - - void setAutoPopupNumberEditor(boolean newValue); - - void setShowNumberEditorButton(boolean newValue); - - void setShowTimeEditorSlider(boolean newValue); - - void setFullScreen(boolean newValue); - - void setChangeSynchroSrc(boolean newValue); - - void setStoreRemoteStorage(boolean newValue); - - void setLoadLocalStorage(boolean newValue); - - void setDefaultDbMode(DbMode newValue); - - void setDefaultCreationMode(CreationMode newValue); - - void setDefaultGpsMaxDelay(int newValue); - - void setDefaultGpsMaxSpeed(float newValue); - - void setLocale(Locale newValue); - - void setDbLocale(Locale newValue); - - void setCanMigrateObstuna(Boolean newValue); - - void setCanMigrateH2(Boolean newValue); - - void setNonTargetObservation(int newValue); - - void setTargetDiscardsObservation(int newValue); - - void setSamplesObservation(int newValue); - - void setObjectsObservation(int newValue); - - void setDetailledActivitiesObservation(int newValue); - - void setMammalsObservation(int newValue); - - void setBirdsObservation(int newValue); - - void setBaitObservation(int newValue); - - void addPropertyChangeListener(PropertyChangeListener listener); - - void addPropertyChangeListener(String propertyName, - PropertyChangeListener listener); - - void removePropertyChangeListener(PropertyChangeListener listener); - - void removePropertyChangeListener(String propertyName, - PropertyChangeListener listener); - - void setShowMigrationSql(boolean showMigrationSql); - - void setShowMigrationProgression(boolean showMigrationProgression); - - void setShowSql(boolean showSql); - - boolean hasListeners(String propertyName); - - PropertyChangeListener[] getPropertyChangeListeners(String propertyName); - - PropertyChangeListener[] getPropertyChangeListeners(); - - String getSpeciesListSeineNonTargetCatchId(); - - String getSpeciesListSeineTargetCatchId(); - - String getSpeciesListSeineSchoolEstimateId(); - - String getSpeciesListSeineObjectObservedSpeciesId(); - - String getSpeciesListSeineObjectSchoolEstimateId(); - - String getSpeciesListLonglineCatchId(); - - String getSpeciesListLonglineEncounterId(); - - String getSpeciesListLonglineDepredatorId(); - - void setSpeciesListSeineNonTargetCatchId(String speciesListSeineNonTargetCatchId); - - void setSpeciesListSeineTargetCatchId(String speciesListSeineTargetCatchId); - - void setSpeciesListSeineSchoolEstimateId(String speciesListSeineSchoolEstimateId); - - void setSpeciesListSeineObjectObservedSpeciesId(String speciesListSeineObjectObservedSpeciesId); - - void setSpeciesListSeineObjectSchoolEstimateId(String speciesListseineObjectSchoolEstimateId); - - void setSpeciesListLonglineCatchId(String speciesListLonglineCatchId); - - void setSpeciesListLonglineEncounterId(String speciesListLonglineEncounterId); - - void setSpeciesListLonglineDepredatorId(String speciesListLonglineDepredatorId); - -} diff --git a/observe-business/src/main/java/fr/ird/observe/ObserveApplicationContext.java b/observe-business/src/main/java/fr/ird/observe/ObserveApplicationContext.java deleted file mode 100644 index d3a1a18..0000000 --- a/observe-business/src/main/java/fr/ird/observe/ObserveApplicationContext.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.entities.constants.ReferenceLocale; -import fr.ird.observe.business.gps.GPSService; -import fr.ird.observe.business.validation.ObserveValidator; -import fr.ird.observe.business.validation.ValidationContext; -import jaxx.runtime.JAXXUtil; -import jaxx.runtime.context.DefaultApplicationContext; -import jaxx.runtime.context.JAXXContextEntryDef; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; - -import java.util.Locale; - -/** - * Le contexte de l'application. - * <p/> - * On définit ici toutes les entrées du contexte applicatif. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ObserveApplicationContext extends DefaultApplicationContext { - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveApplicationContext.class); - - /** the jaxx context entry to store the config */ - public static final JAXXContextEntryDef<IObserveConfig> CONFIG_ENTRY_DEF = - JAXXUtil.newContextEntryDef(IObserveConfig.class); - - /** the jaxx context entry to store the decorator service */ - public static final JAXXContextEntryDef<DecoratorService> DECORATOR_SERVICE_ENTRY_DEF = - JAXXUtil.newContextEntryDef(DecoratorService.class); - - /** the jaxx context entry to store the decorator service */ - public static final JAXXContextEntryDef<BinderService> BINDER_SERVICE_ENTRY_DEF = - JAXXUtil.newContextEntryDef(BinderService.class); - - /** the jaxx context entry to store the gps service */ - public static final JAXXContextEntryDef<GPSService> GPS_SERVICE_ENTRY_DEF = - JAXXUtil.newContextEntryDef(GPSService.class); - - /** the jaxx context entry to store the consolidate data service */ - public static final JAXXContextEntryDef<ConsolidateDataService> CONSOLIDATE_DATA_SERVICE_ENTRY_DEF = - JAXXUtil.newContextEntryDef(ConsolidateDataService.class); - - /** the jaxx context entry to store the data service */ - public static final JAXXContextEntryDef<DataService> DATA_SERVICE_ENTRY_DEF = - JAXXUtil.newContextEntryDef(DataService.class); - - /** the jaxx context entry to store the data service */ - public static final JAXXContextEntryDef<DataContext> DATA_CONTEXT_ENTRY_DEF = - JAXXUtil.newContextEntryDef(DataContext.class); - - /** the jaxx context entry to store the data source (says the ui data source) */ - public static final JAXXContextEntryDef<DataSource> DATA_SOURCE_ENTRY_DEF = - JAXXUtil.newContextEntryDef(DataSource.class); - - public static final JAXXContextEntryDef<ValidationContext> VALIDATION_CONTEXT_ENTRY_DEF = - JAXXUtil.newContextEntryDef(ValidationContext.class); - - public <O> Decorator<O> getDecorator(Class<O> clazz) { - DecoratorService provider = getDecoratorService(); - Decorator<O> value = provider.getDecoratorByType(clazz); - return value; - } - - public <O> Decorator<O> getDecorator(Class<O> clazz, String name) { - DecoratorService provider = getDecoratorService(); - Decorator<O> value = provider.getDecoratorByType(clazz, name); - return value; - } - - public IObserveConfig getConfig() { - return CONFIG_ENTRY_DEF.getContextValue(this); - } - - public final DataSource getDataSource() { - DataSource dataSource = DATA_SOURCE_ENTRY_DEF.getContextValue(this); - return dataSource; - } - - public final void setDataSource(DataSource source) { - if (source == null) { - DATA_SOURCE_ENTRY_DEF.removeContextValue(this); - } else { - DATA_SOURCE_ENTRY_DEF.setContextValue(this, source); - } - } - - public final DecoratorService getDecoratorService() { - DecoratorService decoratorService = - DECORATOR_SERVICE_ENTRY_DEF.getContextValue(this); - if (decoratorService == null) { - - // initialisation du service de décoration - // initialisation - IObserveConfig config = getConfig(); - ReferenceLocale loc = ReferenceLocale.FR; - if (config != null) { - Locale dbLocale = config.getDbLocale(); - if (dbLocale != null) { - loc = ReferenceLocale.valueOf(dbLocale); - } - } - decoratorService = new DecoratorService(loc); - DECORATOR_SERVICE_ENTRY_DEF.setContextValue(this, decoratorService); - } - return decoratorService; - } - - public final DataService getDataService() { - DataService dataService = - DATA_SERVICE_ENTRY_DEF.getContextValue(this); - if (dataService == null) { - dataService = new DataService(); - DATA_SERVICE_ENTRY_DEF.setContextValue(this, dataService); - } - return dataService; - } - - public final BinderService getBinderService() { - BinderService service = BINDER_SERVICE_ENTRY_DEF.getContextValue(this); - if (service == null) { - service = new BinderService(); - BINDER_SERVICE_ENTRY_DEF.setContextValue(this, service); - } - return service; - } - - public final GPSService getGPSService() { - GPSService service = - GPS_SERVICE_ENTRY_DEF.getContextValue(this); - if (service == null) { - service = new GPSService(); - GPS_SERVICE_ENTRY_DEF.setContextValue(this, service); - } - return service; - } - - public ConsolidateDataService getConsolidateDataService() { - - ConsolidateDataService service = - CONSOLIDATE_DATA_SERVICE_ENTRY_DEF.getContextValue(this); - if (service == null) { - service = new ConsolidateDataService(); - CONSOLIDATE_DATA_SERVICE_ENTRY_DEF.setContextValue(this, service); - } - return service; - } - - public final DataContext getDataContext() { - DataContext result = DATA_CONTEXT_ENTRY_DEF.getContextValue(this); - if (result == null) { - result = new DataContext(); - DATA_CONTEXT_ENTRY_DEF.setContextValue(this, result); - } - return result; - } - - public final ValidationContext getValidationContext() { - ValidationContext result = - VALIDATION_CONTEXT_ENTRY_DEF.getContextValue(this); - if (result == null) { - result = new ValidationContext(); - ObserveValidator.setValidationContext(result); - result.setDataContext(getDataContext()); - VALIDATION_CONTEXT_ENTRY_DEF.setContextValue(this, result); - } - return result; - } - - /** - * close the application's context. - * - * @throws Exception if any pb while closing - */ - public void close() throws Exception { - if (log.isDebugEnabled()) { - log.debug("closing context " + this); - } - - // fermeture du context de données - if (getDataSource() != null) { - setDataSource(null); - } - - getValidationContext().closeDataSource(); - - // fermeture des services de persistances ouverts - DataSourceFactory.dispose(); - - // fermeture du context principal - clear(); - - ObserveServiceHelper.close(); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/ObserveServiceHelper.java b/observe-business/src/main/java/fr/ird/observe/ObserveServiceHelper.java deleted file mode 100644 index efb22d1..0000000 --- a/observe-business/src/main/java/fr/ird/observe/ObserveServiceHelper.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import com.google.common.base.Supplier; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.db.ReplicationService; -import fr.ird.observe.db.impl.H2DataSource; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.business.gps.GPSService; -import fr.ird.observe.business.validation.ValidationContext; -import fr.ird.observe.business.validation.ValidationService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.config.ApplicationConfig; - -import java.io.File; -import java.io.IOException; - -import static org.nuiton.i18n.I18n.n; - -public class ObserveServiceHelper { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ObserveServiceHelper.class); - - /** Le context applicatif. */ - public static ObserveApplicationContext context; - - /** Un drapeau pour savoir quand l'application est en cours de fermeture. */ - protected static boolean closed; - - /** - * Un drapeau pour activer sur les connections le support JMX. - * - * @since 2.2 - */ - private static boolean useJMX; - - /** - * Récupération du contexte applicatif. - * - * @return l'instance partagé du contexte. - * @throws IllegalStateException si le contexte n'a pas été initialisé - */ - public static ObserveApplicationContext get() throws IllegalStateException { - checkInit(); - return context; - } - - /** - * @return {@code true} si le context applicatif a été fermé (et est donc - * passé dans la méthode {@link #close()}, {@code false} autrement. - */ - public static boolean isClosed() { - return closed; - } - - /** @return {@code true} si le context a été initialisé */ - public static boolean isInit() { - return context != null; - } - - public static void set(ObserveApplicationContext context) { - if (isInit()) { - throw new IllegalStateException( - "application context already registred."); - } - ObserveServiceHelper.context = context; - - AbstractDataSourceMigration.setApplicationConfigSupplier(new Supplier<ApplicationConfig>() { - @Override - public ApplicationConfig get() { - return ObserveServiceHelper.context.getContextValue(ApplicationConfig.class); - } - }); - - // application non fermée - closed = false; - } - - public static void close() { - if (log.isDebugEnabled()) { - log.debug("Closing service helper..."); - } - context = null; - AbstractDataSourceMigration.setApplicationConfigSupplier(null); - - // application fermée - closed = true; - } - - /** - * Pour instancier un nouveau service de réplication. - * - * @return le nouveau service de réplication - */ - public static ReplicationService newReplicationService() { - return new ReplicationService(); - } - - /** - * Pour instancier un nouveau service de validation. - * - * @return le nouveau service de validation - */ - public static ValidationService newValidationService() { - return new ValidationService(); - } - - public static DataContext getDataContext() { - checkInit(); - ObserveApplicationContext context = get(); - DataContext dataContext = context.getDataContext(); - return dataContext; - } - - public static ValidationContext getValidationContext() { - checkInit(); - ObserveApplicationContext context = get(); - ValidationContext dataContext = context.getValidationContext(); - return dataContext; - } - - /** - * Pour instancier un nouveau service GPS. - * - * @return le service GPS partagé - */ - public static GPSService getGPSService() { - checkInit(); - ObserveApplicationContext context = get(); - GPSService service = context.getGPSService(); - return service; - } - - /** - * Pour récupérer le service de consolidation des données. - * - * @return le service de consolidation des données partagé - */ - public static ConsolidateDataService getConsolidateDataService() { - checkInit(); - ObserveApplicationContext context = get(); - ConsolidateDataService service = context.getConsolidateDataService(); - return service; - - } - - /** - * Pour obtenir l'unique service haut niveau de manipulation des données. - * - * @return le service haut niveau de manipulation des donées. - */ - public static DataService getDataService() { - checkInit(); - ObserveApplicationContext context = get(); - DataService service = context.getDataService(); - return service; - } - - /** - * Pour obtenir l'unique service de décoration. - * - * @return l'instance partagé du service de décoration - */ - public static DecoratorService getDecoratorService() { - checkInit(); - ObserveApplicationContext context = get(); - DecoratorService service = context.getDecoratorService(); - return service; - } - - /** - * Creates a new local temp storage. - * - * @param config the configuration containing the tmp directory to use - * @param label label of storage - * @param prefixName prefix to add directory of local db - * @return the new service NOT opened - * @throws IOException if any pb while configuring the service - */ - public static DataSource newEmptyTempStorage( - IObserveConfig config, - String label, - String prefixName) throws IOException { - String dbfileName = (prefixName == null ? "tmp_" : prefixName + "_") - + System.nanoTime(); - - File dir = new File(config.getTmpDirectory(), dbfileName); - - H2DataSourceConfig conf = DataSourceFactory.newH2ConfigEmpty( - label, - dir, - config.getH2Login(), - config.getH2Password() - ); - - H2DataSource service = DataSourceFactory.newService(conf); - return service; - } - - /** - * Creates a new local temp storage. - * - * @param dir the directory to use to store database - * @param label label of storage - * @return the new service NOT opened - * @throws IOException if any pb while configuring the service - */ - public static DataSource newEmptyTempStorage(File dir, - String label) throws IOException { - - H2DataSourceConfig conf = DataSourceFactory.newH2ConfigEmpty( - label, - dir, - "sa", - "sa".toCharArray() - ); - - H2DataSource service = DataSourceFactory.newService(conf); - return service; - } - - /** - * Construit une source de données sur la base locale de l'application. - * <p/> - * <b>Note:</b> La base locale doit exister, sinon on soulève une - * exeception - * - * @param config la configuration à utiliser - * @return la service de persistance initialisé (mais non ouvert) - * @throws IOException si une erreur d'IO - * @throws IllegalStateException si la base locale n'existe pas - * @see DataSource - */ - public static H2DataSource newLocalStorageService(IObserveConfig config) throws IOException, IllegalStateException { - - - H2DataSourceConfig c = - config.toH2StorageConfig(n("observe.storage.label.local")); - - c.init(); - - if (!c.isStorageExists()) { - throw new IllegalStateException( - "local base must exist, when using this method (" + - c.getStorageDirectory() + ')'); - } - - H2DataSource service = DataSourceFactory.newService(c); - return service; - } - - /** - * Teste si la base locale existe. - * - * @param config la configuration à tester - * @return {@code true} si la base locale existe, {@code false} sinon. - * @throws IOException si pb d'IO - */ - public static boolean isLocalStorageExists(IObserveConfig config) throws IOException { - - // build a local storage service config - H2DataSourceConfig storageConfig = config.toH2StorageConfig( - n("observe.storage.label.local")); - storageConfig.init(); - boolean dbExists = storageConfig.isStorageExists(); - return dbExists; - } - - /** - * Teste si le dump depuis la base obstuna a ete cree. - * <p/> - * Ce dump est cree lors de la premiere creation de base locale a partir - * d'une base distante. - * <p/> - * Une fois ce dump crée, on autorise la création de base locale à partir de - * la base embarquée. Ainsi, on force toujours un premier import de - * référentiel depuis une base distante. - * - * @param config la configuration à utiliser - * @return {@code true} si le dump existe, {@code false} sinon. - */ - public static boolean isInitialDbExists(IObserveConfig config) { - - boolean dbExists = config.getInitialDbDump().exists(); - return dbExists; - } - - /** - * Teste si le context applicatif a bien été initialisé. - * - * @throws IllegalStateException si le context n'a pas été initialisé. - */ - protected static void checkInit() throws IllegalStateException { - if (!isInit()) { - throw new IllegalStateException("no application context initialized."); - } - } - - public static boolean isUseJMX() { - return useJMX; - } - - public static void setUseJMX(boolean useJMX) { - ObserveServiceHelper.useJMX = useJMX; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/ObserveTechnicalException.java b/observe-business/src/main/java/fr/ird/observe/ObserveTechnicalException.java deleted file mode 100644 index 7eb30b0..0000000 --- a/observe-business/src/main/java/fr/ird/observe/ObserveTechnicalException.java +++ /dev/null @@ -1,50 +0,0 @@ -package fr.ird.observe; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -/** - * Created on 8/30/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ObserveTechnicalException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public ObserveTechnicalException() { - } - - public ObserveTechnicalException(String message) { - super(message); - } - - public ObserveTechnicalException(String message, Throwable cause) { - super(message, cause); - } - - public ObserveTechnicalException(Throwable cause) { - super(cause); - } - -} diff --git a/observe-business/src/main/java/fr/ird/observe/SendMessageAble.java b/observe-business/src/main/java/fr/ird/observe/SendMessageAble.java deleted file mode 100644 index 1930156..0000000 --- a/observe-business/src/main/java/fr/ird/observe/SendMessageAble.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -/** - * Un contrat pour pouvoir propager les messages. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5 - */ -public interface SendMessageAble { - - void sendMessage(String message); -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/DataContext.java b/observe-business/src/main/java/fr/ird/observe/db/DataContext.java deleted file mode 100644 index 378a81b..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/DataContext.java +++ /dev/null @@ -1,702 +0,0 @@ -package fr.ird.observe.db; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TripSeine; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.beans.AbstractSerializableBean; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class DataContext extends AbstractSerializableBean { - - public static final String PROPERTY_OPEN_PROGRAM = "openProgram"; - - public static final String PROPERTY_OPEN_TRIP = "openTrip"; - - public static final String PROPERTY_OPEN_ROUTE = "openRoute"; - - public static final String PROPERTY_OPEN_ACTIVITY = "openActivity"; - - public static final String PROPERTY_OPEN_SET = "openSet"; - - public static final String PROPERTY_OPEN_PROGRAM_ID = "openProgramId"; - - public static final String PROPERTY_OPEN_TRIP_ID = "openTripId"; - - public static final String PROPERTY_OPEN_ROUTE_ID = "openRouteId"; - - public static final String PROPERTY_OPEN_ACTIVITY_ID = "openActivityId"; - - public static final String PROPERTY_OPEN_SET_ID = "openSetId"; - - public static final String PROPERTY_SELECTED_PROGRAM_ID = "selectedProgramId"; - - public static final String PROPERTY_SELECTED_TRIP_ID = "selectedTripId"; - - public static final String PROPERTY_SELECTED_ROUTE_ID = "selectedRouteId"; - - public static final String PROPERTY_SELECTED_ACTIVITY_ID = "selectedActivityId"; - - public static final String PROPERTY_SELECTED_SET_ID = "selectedSetId"; - - public static final String PROPERTY_SELECTED_FLOATING_OBJECT_ID = "selectedFloatingObjectId"; - - public static final String PROPERTY_ENABLED = "enabled"; - - public static final String PROPERTY_SELECTION_CHANGED = "selectionChanged"; - - protected String openProgramId; - - protected String openTripId; - - protected String openRouteId; - - protected String openActivityId; - - protected String openSetId; - - protected String selectedProgramId; - - protected String selectedTripId; - - protected String selectedRouteId; - - protected String selectedActivityId; - - protected String selectedSetId; - - protected String selectedFloatingObjectId; - - protected boolean enabled; - - protected boolean selectionChanged; - - protected TripSeine validationTripSeine; - - protected Route validationRoute; - - protected ActivitySeine validationActivitySeine; - - protected SetSeine validationSetSeine; - - protected FloatingObject validationFloatingObject; - - /** Logger */ - private static final Log log = LogFactory.getLog(DataContext.class); - - private static final long serialVersionUID = 1L; - - public String getOpenProgramId() { - return openProgramId; - } - - public void setOpenProgramId(String openProgramId) { - String oldValue = getOpenProgramId(); - boolean oldValue2 = isOpenProgram(); - this.openProgramId = openProgramId; - firePropertyChange(PROPERTY_OPEN_PROGRAM_ID, oldValue, this.openProgramId); - firePropertyChange(PROPERTY_OPEN_PROGRAM, oldValue2, isOpenProgram()); - } - - public String getOpenTripId() { - return openTripId; - } - - public String getOpenTripLonglineId() { - return isOpenTripLongline() ? getOpenTripId() : null; - } - - public String getOpenTripSeineId() { - return isOpenTripSeine() ? getOpenTripId() : null; - } - - - public void setOpenTripId(String openTripId) { - String oldValue = getOpenTripId(); - boolean oldValue2 = isOpenTrip(); - this.openTripId = openTripId; - firePropertyChange(PROPERTY_OPEN_TRIP_ID, oldValue, this.openTripId); - firePropertyChange(PROPERTY_OPEN_TRIP, oldValue2, isOpenTrip()); - } - - public String getOpenRouteId() { - return openRouteId; - } - - public void setOpenRouteId(String openRouteId) { - String oldValue = getOpenRouteId(); - boolean oldValue2 = isOpenRoute(); - this.openRouteId = openRouteId; - firePropertyChange(PROPERTY_OPEN_ROUTE_ID, oldValue, openRouteId); - firePropertyChange(PROPERTY_OPEN_ROUTE, oldValue2, isOpenRoute()); - } - - public String getOpenActivityId() { - return openActivityId; - } - - public String getOpenActivityLonglineId() { - return isOpenActivityLongline() ? getOpenActivityId() : null; - } - - public String getOpenActivitySeineId() { - return isOpenActivitySeine() ? getOpenActivityId() : null; - } - - public void setOpenActivityId(String openActivityId) { - String oldValue = getOpenActivityId(); - boolean oldValue2 = isOpenActivity(); - this.openActivityId = openActivityId; - firePropertyChange(PROPERTY_OPEN_ACTIVITY_ID, oldValue, this.openActivityId); - firePropertyChange(PROPERTY_OPEN_ACTIVITY, oldValue2, isOpenActivity()); - } - - public String getOpenSetId() { - return openSetId; - } - - public String getOpenSetLonglineId() { - return isOpenSetLongline() ? getOpenSetId() : null; - } - - public String getOpenSetSeineId() { - return isOpenSetSeine() ? getOpenSetId() : null; - } - - - public void setOpenSetId(String openSetId) { - String oldValue = getOpenSetId(); - boolean oldValue2 = isOpenSet(); - this.openSetId = openSetId; - firePropertyChange(PROPERTY_OPEN_SET_ID, oldValue, this.openSetId); - firePropertyChange(PROPERTY_OPEN_SET, oldValue2, isOpenSet()); - } - - public String getSelectedProgramId() { - return selectedProgramId; - } - - public void setSelectedProgramId(String selectedProgramId) { - String oldValue = getSelectedProgramId(); - this.selectedProgramId = selectedProgramId; - firePropertyChange(PROPERTY_SELECTED_PROGRAM_ID, oldValue, this.selectedProgramId); - } - - public String getSelectedTripId() { - return selectedTripId; - } - - public String getSelectedTripLonglineId() { - return isSelectedTripLongline() ? getSelectedTripId() : null; - } - - public String getSelectedTripSeineId() { - return isSelectedTripSeine() ? getSelectedTripId() : null; - } - - public void setSelectedTripId(String selectedTripId) { - String oldValue = getSelectedTripId(); - this.selectedTripId = selectedTripId; - firePropertyChange(PROPERTY_SELECTED_TRIP_ID, oldValue, this.selectedTripId); - } - - public boolean isSelectedTripLongline() { - return selectedTripId != null && Entities.isLonglineId(selectedTripId); - } - - public boolean isSelectedTripSeine() { - return selectedTripId != null && Entities.isSeineId(selectedTripId); - } - - public String getSelectedRouteId() { - return selectedRouteId; - } - - public void setSelectedRouteId(String selectedRouteId) { - String oldValue = getSelectedRouteId(); - this.selectedRouteId = selectedRouteId; - firePropertyChange(PROPERTY_SELECTED_ROUTE_ID, oldValue, selectedRouteId); - } - - public String getSelectedActivityId() { - return selectedActivityId; - } - - public String getSelectedActivityLonglineId() { - return isSelectedActivityLongline() ? getSelectedActivityId() : null; - } - - public String getSelectedActivitySeineId() { - return isSelectedActivitySeine() ? getSelectedActivityId() : null; - } - - public boolean isSelectedActivityLongline() { - return selectedActivityId != null && Entities.isLonglineId(selectedActivityId); - } - - public boolean isSelectedActivitySeine() { - return selectedActivityId != null && Entities.isSeineId(selectedActivityId); - } - - public void setSelectedActivityId(String selectedActivityId) { - String oldValue = getSelectedActivityId(); - this.selectedActivityId = selectedActivityId; - firePropertyChange(PROPERTY_SELECTED_ACTIVITY_ID, oldValue, this.selectedActivityId); - } - - public String getSelectedSetId() { - return selectedSetId; - } - - public String getSelectedSetLonglineId() { - return isSelectedActivityLongline() ? getSelectedSetId() : null; - } - - public String getSelectedSetSeineId() { - return isSelectedActivitySeine() ? getSelectedSetId() : null; - } - - public void setSelectedSetId(String selectedSetId) { - String oldValue = getSelectedSetId(); - this.selectedSetId = selectedSetId; - firePropertyChange(PROPERTY_SELECTED_SET_ID, oldValue, this.selectedSetId); - } - - public String getSelectedFloatingObjectId() { - return selectedFloatingObjectId; - } - - public void setSelectedFloatingObjectId(String selectedFloatingObjectId) { - String oldValue = getSelectedFloatingObjectId(); - this.selectedFloatingObjectId = selectedFloatingObjectId; - firePropertyChange(PROPERTY_SELECTED_FLOATING_OBJECT_ID, oldValue, this.selectedFloatingObjectId); - } - - public boolean isEnabled() { - return enabled; - } - - public boolean getEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - boolean oldValue = getEnabled(); - this.enabled = enabled; - firePropertyChange(PROPERTY_ENABLED, oldValue, enabled); - } - - public boolean isSelectionChanged() { - return selectionChanged; - } - - public boolean getSelectionChanged() { - return selectionChanged; - } - - public void setSelectionChanged(boolean selectionChanged) { - boolean oldValue = getSelectionChanged(); - this.selectionChanged = selectionChanged; - firePropertyChange(PROPERTY_SELECTION_CHANGED, oldValue, selectionChanged); - } - - public DataContext() { - } - - static DataContextType[] types; - - static DataContextType[] reverseTypes; - - public DataContextType[] getTypes() { - if (types == null) { - types = DataContextType.values(); - } - return types; - } - - public DataContextType[] getReverseTypes() { - if (reverseTypes == null) { - List<DataContextType> list = Arrays.asList(DataContextType.values()); - Collections.reverse(list); - reverseTypes = list.toArray(new DataContextType[list.size()]); - } - - return reverseTypes; - } - - public String getHigherOpenId() { - for (DataContextType type : getReverseTypes()) { - String result = type.getOpenId(this); - if (result != null) { - return result; - } - } - return null; - } - - public String getHigherSelectedId() { - - for (DataContextType type : getReverseTypes()) { - String result = type.getSelectedId(this); - if (result != null) { - return result; - } - } - return null; - } - - public String[] getSelectedIds() { - - List<String> ids = new ArrayList<String>(); - - for (DataContextType type : getTypes()) { - String result = type.getSelectedId(this); - if (result != null) { - ids.add(result); - } - } - return ids.toArray(new String[ids.size()]); - } - - public String[] getOpenIds() { - - List<String> ids = new ArrayList<String>(); - - for (DataContextType type : getTypes()) { - String result = type.getOpenId(this); - if (result != null) { - ids.add(result); - } - } - return ids.toArray(new String[ids.size()]); - } - - public String[] getOpenIds(Class<?> type) { - - String[] result = null; - - if (isOpenProgram()) { - - List<String> ids = new ArrayList<String>(); - ids.add(getOpenProgramId()); - - if (!Program.class.equals(type) && isOpenTrip()) { - - String tripId = getOpenTripId(); - ids.add(tripId); - - if (tripId.startsWith(TripSeine.class.getName())) { - - // on a seine trip - if (!TripSeine.class.equals(type) && isOpenRoute()) { - ids.add(getOpenRouteId()); - if (!Route.class.equals(type) && isOpenActivitySeine()) { - ids.add(getOpenActivitySeineId()); - if (!ActivitySeine.class.equals(type) && isOpenSetSeine()) { - ids.add(getOpenSetSeineId()); - } - } - } - - } else { - - // on a longline trip - if (!TripLongline.class.equals(type) && isOpenActivityLongline()) { - ids.add(getOpenActivityLonglineId()); - if (!ActivityLongline.class.equals(type) && isOpenSetLongline()) { - ids.add(getOpenSetLonglineId()); - } - - } - - } - - } - - result = ids.toArray(new String[ids.size()]); - - } - - return result; - } - - public boolean isOpenProgram() { - return openProgramId != null; - } - - public boolean isOpenTrip() { - return openTripId != null; - } - - public boolean isOpenTripLongline() { - return isOpenTrip() && Entities.isLonglineId(openTripId); - } - - public boolean isOpenTripSeine() { - return isOpenTrip() && Entities.isSeineId(openTripId); - } - - public boolean isOpenRoute() { - return openRouteId != null; - } - - public boolean isOpenActivity() { - return openActivityId != null; - } - - public boolean isOpenActivityLongline() { - return isOpenActivity() && Entities.isLonglineId(openActivityId); - } - - public boolean isOpenActivitySeine() { - return isOpenActivity() && Entities.isSeineId(openActivityId); - } - - - public boolean isOpenSet() { - return openSetId != null; - } - - public boolean isOpenSetLongline() { - return isOpenSet() && Entities.isLonglineId(openSetId); - } - - public boolean isOpenSetSeine() { - return isOpenSet() && Entities.isSeineId(openSetId); - } - - public boolean isSelectedOpen(Class<?> type) { - - for (DataContextType entityType : DataContextType.values()) { - if (entityType.acceptType(type)) { - - // bon type trouve - - String openId = entityType.getOpenId(this); - String selectedId = entityType.getSelectedId(this); - if (selectedId == null || openId == null) { - - // pas selectionne ou rien d'ouvert - return false; - } - - return selectedId.equals(openId); - } - } - - // type non trouve - return false; - } - - public void populateSelectedIds(String... selectedId) { - - List<String> oldSelection = Arrays.asList(getSelectedIds()); - - if (log.isDebugEnabled()) { - log.debug("old selection = " + oldSelection); - } - - // on nettoye toujours toutes les anciennes sélections - // avant de positionner les nouvelles - resetSelect(); - - List<String> realSelection = null; - if (selectedId != null && selectedId.length > 0) { - - realSelection = new ArrayList<String>(); - for (String s : selectedId) { - if (s == null) { - - // ce cas peut arriver lors de la creation d'un nouvel objet - continue; - } - DataContextType type = DataContextType.acceptId(s); - if (type == null) { - - if (log.isWarnEnabled()) { - log.warn("Could not find type for id : " + s); - } - continue; - } - - type.setSelectedId(this, s); - realSelection.add(s); - if (log.isDebugEnabled()) { - log.debug("add selectedId : " + s); - } - } - } - - if (oldSelection.equals(realSelection)) { - - // rien a change - if (log.isDebugEnabled()) { - log.debug("selection does not changed"); - } - return; - } - - if (log.isInfoEnabled()) { - log.info("new selection = " + realSelection); - } - - // on change toujours l'état de selection - - setSelectionChanged(true); - } - - public void populateOpens(String... openIds) { - if (!getEnabled()) { - - if (log.isWarnEnabled()) { - log.warn(this + " is not enabled"); - } - // service non initialisé - resetOpen(); - return; - } - - List<String> oldSelection = Arrays.asList(getOpenIds()); - List<String> realSelection = new ArrayList<String>(); - - if (openIds != null && openIds.length > 0) { - - for (String s : openIds) { - if (s == null) { - - // ce cas peut arriver lors de la creation d'un nouvel objet - continue; - } - DataContextType type = DataContextType.acceptId(s); - if (type == null) { - - if (log.isWarnEnabled()) { - log.warn("Could not find type for id : " + s); - } - continue; - } - - if (!type.canOpen()) { - - // pas de traitement open - continue; - } - - type.setOpenId(this, s); - realSelection.add(s); - if (log.isDebugEnabled()) { - log.debug("add openId : " + s); - } - } - } - - if (oldSelection.equals(realSelection)) { - - // rien a change - if (log.isDebugEnabled()) { - log.debug("openIds selection does not changed"); - } - return; - } - - if (log.isInfoEnabled()) { - log.info("new openIds selection = " + realSelection); - log.info("old openIds selection = " + oldSelection); - } - - for (String s : oldSelection) { - - if (realSelection.contains(s)) { - // pas bouge rien a faire - continue; - } - - DataContextType type = DataContextType.acceptId(s); - if (type == null) { - - if (log.isWarnEnabled()) { - log.warn("Could not find type for id : " + s); - } - continue; - } - - if (!type.canOpen()) { - - // pas de traitement open - continue; - } - - String newId = type.getOpenId(this); - if (newId != null) { - - if (log.isInfoEnabled()) { - log.info("will remove old obsolete open id : " + s); - } - - // plus d'id pour ce type, on le supprime - type.setOpenId(this, null); - } - } - } - - protected void reset() { - resetOpen(); - resetSelect(); - } - - protected void resetSelect() { - setSelectedProgramId(null); - setSelectedTripId(null); - setSelectedRouteId(null); - setSelectedActivityId(null); - setSelectedFloatingObjectId(null); - setSelectedSetId(null); - selectionChanged = false; - } - - protected void resetOpen() { - setOpenProgramId(null); - setOpenTripId(null); - setOpenRouteId(null); - setOpenActivityId(null); - } - - protected void firePropertyChange(String propertyName, Object newValue) { - firePropertyChange(propertyName, null, newValue); - } - -} //DataContext diff --git a/observe-business/src/main/java/fr/ird/observe/db/DataSource.java b/observe-business/src/main/java/fr/ird/observe/db/DataSource.java deleted file mode 100644 index 35fa269..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/DataSource.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.db.constants.DataSourceState; -import fr.ird.observe.db.event.DataSourceEvent; -import fr.ird.observe.db.event.DataSourceListener; -import fr.ird.observe.entities.OpenableEntity; -import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.framework.TopiaService; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.version.Version; - -import java.io.File; -import java.util.List; -import java.util.Properties; - -/** - * Le contrat d'une source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface DataSource { - - String OPEN_PROPERTY_KEY = "open"; - - String REFERENTIEL_PROPERTY_KEY = "referentiel"; - - String DATA_PROPERTY_KEY = "data"; - - // ------------------------------------------------------------------------- - // Methodes de démarrage et fermeture de la source de données - // ------------------------------------------------------------------------- - - /** - * Pour initialiser le service sans l'ouvrir. - * <p/> - * Note: cette opération est délégué à la configuration. - * <p/> - * A la fin de cette méthode, l'état doit être {@link - * DataSourceState#INIT} si - * tout s'est bien déroulé. - * - * @see DataSourceConfig#init() - */ - void init(); - - /** - * Ouvre le service. - * <p/> - * Après cette opération, le service doit être en état {@link - * DataSourceState#OPEN} si - * tout s'est bien déroulé. - * - * @throws DataSourceException si pb - */ - void doOpen() throws DataSourceException; - - /** - * Ferme le service. - * <p/> - * Après cette opération, le service doit être en état {@link - * DataSourceState#CLOSED} - * - * @param destroy drapeau pour savoir si on doit détruire la base après - * fermeture. - * @throws DataSourceException if pb - */ - void doClose(boolean destroy) throws DataSourceException; - - // ------------------------------------------------------------------------- - // Methodes d'accès aux état internes de la source de données - // ------------------------------------------------------------------------- - - /** - * Recupère la version de la base. (ne peut pas être utilisé avant que la - * base soit ouverte). - * <p/> - * Note: si la base n'est pas versionnée, la version est nulle. - * - * @return la version de la base, ou <code>null</code> si la base n'est pas - * versionnee - * @throws DataSourceException if pb - */ - Version getDbVersion() throws DataSourceException; - - /** @return le libellé court du service */ - String getShortLabel(); - - /** @return le libellé complet du service */ - String getLabel(); - - /** - * @return {@code true} si le service est ouvert (i.e qu'il y a une - * connection ouverte vers la base). - */ - boolean isOpen(); - - boolean wasClosed(); - - /** @return la configuration du service */ - DataSourceConfig getConfig(); - - /** @return {@code true} si on peut lire le référentiel */ - boolean canReadReferentiel(); - - /** @return {@code true} si on peut écrire sur le référentiel */ - boolean canWriteReferentiel(); - - /** @return {@code true} si on peut lire les donées observer */ - boolean canReadData(); - - /** @return {@code true} si on peut écrire des données observer */ - boolean canWriteData(); - - Properties getConfigForTopia(); - - // ------------------------------------------------------------------------- - // Methodes de manipulation des transactions, DAO et TopiaService - // ------------------------------------------------------------------------- - - /** @return le parent de tous les context topia. */ - TopiaContext getRootCtxt(); - - TopiaContext beginTransaction(String methodName) throws DataSourceException; - - void rollbackTransaction(TopiaContext context, - String methodName) throws DataSourceException; - - void commitTransaction(TopiaContext context, - String methodName) throws DataSourceException; - - void closeTransaction(TopiaContext context, - String methodName) throws DataSourceException; - - ReplicationService getReplicationService(); - - <S extends TopiaService> S getTopiaService(Class<S> serviceType); - - <P extends TopiaEntity> TopiaDAO<P> getDAO(TopiaContext context, - Class<P> entityType) throws TopiaException; - - <P extends TopiaEntity> TopiaDAO<P> getDAO(TopiaContext context, - P entity) throws TopiaException; - - <E extends OpenableEntity & TopiaEntity> E getOpen(TopiaContext tx, - Class<E> klass) throws DataSourceException; - - String[] getOpenIds(TopiaContext tx) throws DataSourceException; - - /** - * Exporte la base de données dans un script gzip-compresse. - * <p/> - * Note : Actuellement, seul esl bases de type H2 peuvent utiliser cette - * fonctionnalitee. - * - * @param gzipFile le fichier ou ecrire le script gzippe - * @throws DataSourceException si un pb pendant l'objectOperation - */ - void storeDB(File gzipFile) throws DataSourceException; - - /** - * Décore un obet persistant. - * - * @param tx la transaction à utiliser (si elle est nulle on en crée une que l'on ferme avant la fin de l'appel). - * @param id l'id de l'obet à décorer - * @param decorator le décorateur - * @return la décoration - * @throws DataSourceException si pas possible de récupérer l'objet en base - */ - String decorateEntity(TopiaContext tx, - String id, - Decorator<?> decorator) throws DataSourceException; - - <E extends TopiaEntity> List<E> loadDecoratedEntities(TopiaContext tx, - Class<E> entityClass, - Decorator<E> decorator) throws DataSourceException; - - // ------------------------------------------------------------------------- - // Methodes de vérification d'état - // ------------------------------------------------------------------------- - - /** - * Verifie que l'etat du service est l'un de ceux donnes en parametre. - * - * @param state les etats acceptes - * @throws IllegalStateException si l'etat du service n'est pas l'un de ceux - * donnes en parametre - */ - void checkState(DataSourceState... state) throws IllegalStateException; - - // ------------------------------------------------------------------------- - // Methodes de l'api des écouteurs sur évènement sur source de données - // ------------------------------------------------------------------------- - - void addDataSourceListener(DataSourceListener listener); - - boolean containsDataSourceListener(DataSourceListener listener); - - void removeDataSourceListener(DataSourceListener listener); - - DataSourceListener[] getDataSourceListeners(); - - void fireNewMessage(String message); - - void fireNewMessage(String message, DataSourceEvent.MessageLevel level); - - <E> E findByTopiaId(TopiaContext tx, String entityId) throws TopiaException; -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/DataSourceConfig.java b/observe-business/src/main/java/fr/ird/observe/db/DataSourceConfig.java deleted file mode 100644 index c082e06..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/DataSourceConfig.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DataPolicy; -import fr.ird.observe.db.constants.DataSourceState; - -import java.util.EnumSet; -import java.util.Properties; -import java.util.Set; - -/** - * Le contrat de la configuration d'une source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface DataSourceConfig extends Cloneable { - - /** - * Récupère la valeur d'un paramètre. - * - * @param <T> le type de la valeur d'un paramètre - * @param param la définition du paramètre - * @param type le type du paramètre - * @return la valeur du paramètre - */ - <T> T get(DataSourceConfigParam param, Class<T> type); - - /** - * Positionne une nouvelle valeur pour unparamètre donné. - * <p/> - * Note: si on passe la valeur <code>null</code> alors le paramètre ne sera - * plus utilisé (jusqu'à ré-affectation d'un valeur non nulle). - * - * @param param la définition du paramètre - * @param value la nouvelle valeur à positionner - */ - void set(DataSourceConfigParam param, Object value); - - /** - * Prépare l'utilisation de la configuration sans ouvrir aucun connexion - * vers la base de données associée. - * <p/> - * A la fin de cette méthode, l'état doit être {@link - * DataSourceState#INIT} si - * tout s'est bien déroulé. - */ - void init(); - - /** @return la configuration sous forme l'un fichier de properties. */ - Properties getDbConfig(); - - /** - * Méthode pour valider la configuration. - * <p/> - * Cette méthode doit être appelée par le service avant toute ouverture de - * service pour assurer que l'on obtiendra un service valide. - * - * @return {@code true} si la configuration est valide. - */ - boolean isValid(); - - /** - * @return {@code true} si le service de persistance utilise un cache - * sur les entités du référentiel. - */ - boolean isUseCache(); - - /** @return le label court de la source de donnees. */ - String getShortLabel(); - - /** @return le label long de la source de donnees. */ - String getLabel(); - - /** @return le login pour se connecter a la base */ - String getLogin(); - - /** @return le mot de passe pour se connecter a la base */ - char[] getPassword(); - - /** - * @return {@code true} si on doit effectuer une tentative de mise a - * jour de la base a l'ouverture du service. - */ - boolean isCanMigrate(); - - boolean isShowMigrationSql(); - - boolean isShowMigrationProgression(); - - void setShowMigrationSql(boolean showSql); - - void setShowMigrationProgression(boolean showProgression); - - /** - * Positionne le login de connexion. - * - * @param login le nouveau login de connexion - */ - void setLogin(String login); - - /** - * Positionne le mot de passe de connexion. - * - * @param password le nouveau mot de passe de connexion - */ - void setPassword(char[] password); - - /** - * Positionne le label court de la source de donnees. - * - * @param shortLabel le nouvel label court de la source de donnes. - */ - void setShortLabel(String shortLabel); - - /** - * Positionne le drapeau d'utilisation du cache des entites. - * <p/> - * Il s'agit d'un cache sur le referentiel, mise a jour a chaque - * modification sur une entite du referentiel. - * <p/> - * Sera util lorsque l'on editera le referentiel dans l'application. - * - * @param useCache la nouvelle valeur du drapeau - */ - void setUseCache(boolean useCache); - - /** @return une instance clonee de la configuration */ - DataSourceConfig clone(); - - /** - * Recopie cette configuration vers la configuratyion donnee en parametre. - * - * @param config la configuration destination - */ - void copyTo(DataSourceConfig config); - - /** @return les droits sur la source de donnees */ - EnumSet<DataPolicy> getPolicy(); - - /** - * Recupère les droits utilisables sur ce service de persistance. - * <p/> - * La liste des droits sera positionné dans le champ {@link #getPolicy()}. - * <p/> - * Cette méthode est appellé à l'ouverture du service si la connexion a bien - * été établie. - */ - void detectPolicy(); - - /** @return les droits sur la source de donnees formates. */ - String getPolicyLabel(); - - void fillWrights(StringBuilder buffer, boolean read, - boolean write, String label); - - /** - * @param canMigrate pour indiquer si on doit effecuter une tentative de - * mise a jour a l'ouverture du service. - */ - void setCanMigrate(boolean canMigrate); - - boolean isCanReadData(); - - boolean isCanReadReferentiel(); - - boolean isCanWriteData(); - - boolean isCanWriteReferentiel(); - - CreationMode getCreationMode(); - - void setCreationMode(CreationMode creationMode); - - DataSourceConfig getImportConfig(); - - void setImportConfig(DataSourceConfig importConfig); - - DataSourceConfig getImportDataConfig(); - - void setImportDataConfig(DataSourceConfig importDataConfig); - - Set<String> getImportDataIds(); - - void setImportDataIds(Set<String> importDataIds); - -// boolean hasH2ImportConfig(); -// -// boolean hasPGImportConfig(); - - boolean hasImportReferentielConfig(); - - boolean hasImportDataConfig(); - -// H2DataSourceConfig getH2ImportConfig(); -// -// PGDataSourceConfig getPGImportConfig(); -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/DataSourceConfigParam.java b/observe-business/src/main/java/fr/ird/observe/db/DataSourceConfigParam.java deleted file mode 100644 index 2f1acd1..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/DataSourceConfigParam.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -/** - * Le contrat d'un paramètre de la configuration d'une source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface DataSourceConfigParam { - - /** - * @return le lastName de la clef utilisée pour stocker la valeur de la - * propriété. - */ - String getMapName(); - - /** @return le lastName de la propriété. */ - String getPropertyName(); - - /** @return le type de la propriété. */ - Class<?> getType(); -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/DataSourceException.java b/observe-business/src/main/java/fr/ird/observe/db/DataSourceException.java deleted file mode 100644 index 2782db7..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/DataSourceException.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -/** - * L'exception déclanché lors de l'accès aux méthodes de la source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataSourceException extends Exception { - - private final static long serialVersionUID = 1L; - - protected final String methodName; - - public DataSourceException(String message, String methodName) { - super(message); - this.methodName = methodName; - } - - public DataSourceException(Throwable cause, String methodName) { - super(cause); - this.methodName = methodName; - } - - public DataSourceException(String message, Throwable cause, String methodName) { - super(message, cause); - this.methodName = methodName; - } - - public String getMethodName() { - return methodName; - } - -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/DataSourceFactory.java b/observe-business/src/main/java/fr/ird/observe/db/DataSourceFactory.java deleted file mode 100644 index 1a9961a..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/DataSourceFactory.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.db.constants.CommonDataSourceConfigParam; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.event.DataSourceEvent; -import fr.ird.observe.db.event.DataSourceListener; -import fr.ird.observe.db.event.DataSourceListenerAdapter; -import fr.ird.observe.db.impl.H2DataSource; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.db.impl.H2DataSourceConfigParam; -import fr.ird.observe.db.impl.PGDataSource; -import fr.ird.observe.db.impl.PGDataSourceConfig; -import fr.ird.observe.db.impl.PGDataSourceConfigParam; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.File; -import java.net.URL; -import java.util.Collections; -import java.util.HashSet; -import java.util.ServiceLoader; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * L'usine de source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataSourceFactory { - - /** Logger */ - private static final Log log = - LogFactory.getLog(DataSourceFactory.class); - - /** l'ensemble des proversId découverts */ - protected static Set<DataSourceProvider<?, ?>> proversId; - - /** l'ensemble des services actuellement ouverts */ - protected static final Set<DataSource> services = - new HashSet<DataSource>(); - - /** - * un ecouteur sur les services pour mettre à jour la liste des services - * actifs - */ - protected static final DataSourceListener l = - new DataSourceListenerAdapter() { - - @Override - public void onClosed(DataSourceEvent event) { - DataSource s = event.getSource(); - if (log.isDebugEnabled()) { - log.debug("remove active service " + s.getLabel()); - } - services.remove(s); - } - - @Override - public void onOpened(DataSourceEvent event) { - DataSource s = event.getSource(); - if (log.isDebugEnabled()) { - log.debug("add active service " + s.getLabel()); - } - services.add(s); - } - - @Override - public void onNewMessage(DataSourceEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getMessage()); - } - } - }; - -// public static Version getDbVersion() { -// if (ObserveServiceHelper.context != null) { -// ApplicationConfig config; -// config = ObserveServiceHelper.context.getContextValue(ApplicationConfig.class); -// if (config != null) { -// return config.getOption(Version.class, -// AbstractDataSourceMigration.DB_VERSION); -// } -// } -// return null; -// } - - /** - * @param label le label du service de persistance - * @param params les paramètres de la configuration - * @return la configuration instanciée - */ - public static H2DataSourceConfig newH2Config(String label, Object... params) { - - H2DataSourceConfig config = newConfig(label, - H2DataSourceConfig.class, - H2DataSource.class, - params - ); - - return config; - } - - /** - * @param label le label du service de persistance - * @param params les paramètres de la configuration - * @return la configuration instanciée - */ - public static PGDataSourceConfig newPGConfig(String label, Object... params) { - - PGDataSourceConfig config = newConfig(label, - PGDataSourceConfig.class, - PGDataSource.class, - params - ); - - return config; - } - - public static PGDataSource newService(PGDataSourceConfig config) { - - PGDataSource service = newService(config, PGDataSource.class); - - return service; - } - - public static H2DataSource newService(H2DataSourceConfig config) { - - H2DataSource service = newService(config, H2DataSource.class); - - return service; - } - - public static DataSource newService(DataSourceConfig config) { - - DataSource service = null; - - if (config instanceof H2DataSourceConfig) { - service = newService((H2DataSourceConfig) config); - } else if (config instanceof PGDataSourceConfig) { - service = newService((PGDataSourceConfig) config); - } - - return service; - } - - /** - * @param <C> le type de la configuration - * @param label le label du service de persistance - * @param configClass le type de configuration - * @param serviceClass le type de service - * @param params les paramètres de la configuration - * @return la configuration instanciée - */ - private static <C extends DataSourceConfig, S extends DataSource> C newConfig(String label, - Class<C> configClass, - Class<S> serviceClass, - Object... params) { - - DataSourceProvider<C, S> provider = - getProvider(configClass, serviceClass); - - C config = provider.newConfig(label, params); - - return config; - } - - public static <C extends DataSourceConfig, S extends DataSource> S - newService(C config, Class<S> serviceClass) { - - DataSourceProvider<C, S> provider = getProvider(config, serviceClass); - - S service = provider.newService(config); - - service.addDataSourceListener(l); - - service.init(); - - return service; - } - - public static Set<DataSourceProvider<?, ?>> getProversId() { - if (proversId == null) { - proversId = discover(); - } - return proversId; - } - - public static void dispose() throws DataSourceException { - if (log.isInfoEnabled()) { - log.info("close all services (" + services.size() + ')'); - } - - for (DataSource service : services) { - // on supprime le listener qui met a jour la liste de services - // sinon on entre en concurrence de modification - service.removeDataSourceListener(l); - if (service.isOpen()) { - service.doClose(false); - } - } - services.clear(); - } - - @SuppressWarnings("unchecked") - protected static <C extends DataSourceConfig, S extends DataSource> - DataSourceProvider<C, S> getProvider(Class<C> configClass, - Class<S> serviceClass) { - - if (configClass == null) { - throw new NullPointerException("configClass can not be null"); - } - - if (serviceClass == null) { - throw new NullPointerException("serviceClass can not be null"); - } - - for (DataSourceProvider<?, ?> p : getProversId()) { - if (configClass.equals(p.getConfigClass()) && - serviceClass.equals(p.getServiceClass())) { - return (DataSourceProvider<C, S>) p; - } - } - return null; - } - - @SuppressWarnings("unchecked") - protected static <C extends DataSourceConfig, S extends DataSource> - DataSourceProvider<C, S> getProvider(C config, - Class<S> serviceClass) { - - if (config == null) { - throw new NullPointerException("config can not be null"); - } - - if (serviceClass == null) { - throw new NullPointerException("serviceClass can not be null"); - } - - Class<C> configClass = (Class<C>) config.getClass(); - return getProvider(configClass, serviceClass); - } - - protected static Set<DataSourceProvider<?, ?>> discover() { - Set<DataSourceProvider<?, ?>> detected; - detected = new HashSet<DataSourceProvider<?, ?>>(); - if (log.isDebugEnabled()) { - log.debug("init " + DataSourceFactory.class); - } - for (DataSourceProvider<?, ?> p : ServiceLoader.load(DataSourceProvider.class)) { - detected.add(p); - if (log.isDebugEnabled()) { - log.debug(t("observe.storage.message.provider.detected", p.getServiceClass().getName())); - } - } - - return Collections.unmodifiableSet(detected); - } - - /** - * Creates the config for an empty local storage. - * - * @param label label of storage - * @param dir directory of the database - * @param login login to connect ot the storage - * @param password password to connect ot the storage - * @return the instanciate config - */ - public static H2DataSourceConfig newH2ConfigEmpty( - String label, - File dir, - String login, - char[] password) { - H2DataSourceConfig config = newH2Config( - label, - CommonDataSourceConfigParam.LOGIN, login, - CommonDataSourceConfigParam.PASSWORD, password, - CommonDataSourceConfigParam.CREATION_MODE, CreationMode.EMPTY, - H2DataSourceConfigParam.DIRECTORY, dir - ); - return config; - } - - /** - * Creates the config for a new local storage loaded from the given {@code - * dump}. - * - * @param label label of storage - * @param dir directory of the database - * @param dump url of the dump to load - * @param login login to connect ot the storage - * @param password password to connect ot the storage - * @param canMigrate flag to migrate db if required - * @return the instanciate config - */ - public static H2DataSourceConfig newH2ConfigFromDump( - String label, - File dir, - URL dump, - String login, - char[] password, - boolean canMigrate) { - H2DataSourceConfig config = newH2Config( - label, - CommonDataSourceConfigParam.LOGIN, login, - CommonDataSourceConfigParam.PASSWORD, password, - CommonDataSourceConfigParam.CREATION_MODE, CreationMode.IMPORT_EXTERNAL_DUMP, - H2DataSourceConfigParam.DUMP, dump, - H2DataSourceConfigParam.DIRECTORY, dir, - CommonDataSourceConfigParam.CAN_MIGRATE, canMigrate - ); - return config; - } - - /** - * Creates the config for an existing local storage with migration if - * required. - * - * @param label label of storage - * @param dir directory of the database - * @param login login to connect ot the storage - * @param password password to connect ot the storage - * @param canMigrate flag to update database - * @return the instanciate config - */ - public static H2DataSourceConfig newH2ConfigUseLocalStorage( - String label, - File dir, - String login, - char[] password, - boolean canMigrate) { - H2DataSourceConfig config = newH2Config( - label, - CommonDataSourceConfigParam.LOGIN, login, - CommonDataSourceConfigParam.PASSWORD, password, - H2DataSourceConfigParam.DIRECTORY, dir, - CommonDataSourceConfigParam.CAN_MIGRATE, canMigrate - ); - return config; - } - - /** - * Creates the config for an new local storage with a copy of the - * referentiel of local storage given his {@code importConfig} with - * migration if required. - * - * @param label label of storage - * @param dir directory of the database - * @param importConfig import service configuration - * @param login login to connect ot the storage - * @param password password to connect ot the storage - * @param canMigrate flag to allow migration - * @return the instanciate config - */ - public static H2DataSourceConfig newH2ConfigImportLocalStorage( - String label, - File dir, - H2DataSourceConfig importConfig, - String login, - char[] password, - boolean canMigrate) { - H2DataSourceConfig config = newH2Config( - label, - CommonDataSourceConfigParam.LOGIN, login, - CommonDataSourceConfigParam.PASSWORD, password, - CommonDataSourceConfigParam.CREATION_MODE, CreationMode.IMPORT_LOCAL_STORAGE, - H2DataSourceConfigParam.DIRECTORY, dir, - CommonDataSourceConfigParam.IMPORT_CONFIG, importConfig, - CommonDataSourceConfigParam.CAN_MIGRATE, canMigrate - ); - return config; - } - - /** - * Creates the config for an new local storage with a copy of the - * referentiel of remote storage given his {@code importConfig} with - * migration if required. - * - * @param label label of storage - * @param dir directory of the database - * @param importConfig import service configuration - * @param login login to connect ot the storage - * @param password password to connect ot the storage - * @param canMigrate flag to allow migration - * @return the instanciate config - */ - public static H2DataSourceConfig newH2ConfigImportRemoteStorage( - String label, - File dir, - PGDataSourceConfig importConfig, - String login, - char[] password, - boolean canMigrate) { - H2DataSourceConfig config = newH2Config( - label, - CommonDataSourceConfigParam.LOGIN, login, - CommonDataSourceConfigParam.PASSWORD, password, - CommonDataSourceConfigParam.CREATION_MODE, CreationMode.IMPORT_REMOTE_STORAGE, - H2DataSourceConfigParam.DIRECTORY, dir, - CommonDataSourceConfigParam.IMPORT_CONFIG, importConfig, - CommonDataSourceConfigParam.CAN_MIGRATE, canMigrate - ); - return config; - } - - /** - * Creates a configuration to connect to a remote dn. - * - * @param dbName storage label - * @param login login to connect remote db - * @param password password to connect remote db - * @param url url of remote db - * @param canMigrate flag to allow migration - * @return the new instanciated configuration - */ - public static PGDataSourceConfig newPGConfig( - String dbName, - String login, - char[] password, - String url, - boolean canMigrate) { - - PGDataSourceConfig config = newPGConfig( - dbName, - CommonDataSourceConfigParam.LOGIN, login, - CommonDataSourceConfigParam.PASSWORD, password, - PGDataSourceConfigParam.URL, url, - CommonDataSourceConfigParam.CAN_MIGRATE, canMigrate - ); - - return config; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/DataSourceProvider.java b/observe-business/src/main/java/fr/ird/observe/db/DataSourceProvider.java deleted file mode 100644 index e4fdb1c..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/DataSourceProvider.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import org.hibernate.dialect.Dialect; - -import java.sql.Driver; - -/** - * Le contrat d'un provider de source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface DataSourceProvider<C extends DataSourceConfig, S extends DataSource> { - - /** @return le type de configuration que le provider peut fournir. */ - Class<C> getConfigClass(); - - /** @return le type de service que le provider peut fournir. */ - Class<S> getServiceClass(); - - /** @return le dialect hibernate utilisé */ - Class<? extends Dialect> getDialectClass(); - - /** @return le driver sql du service */ - Class<? extends Driver> getDriverClass(); - - /** @return la classe de migration */ - Class<? extends AbstractDataSourceMigration> getMigrationClass(); - - /** @return les paramètres utilisables sur la configuration */ - DataSourceConfigParam[] getParams(); - - /** - * Pour créer une nouvelle configuration. - * - * @param label le libellé du service - * @param params les paramètres de la configuration - * @return la nouvelle configuration instanciée mais non initialisée. - */ - C newConfig(String label, Object... params); - - /** - * Pour créer un nouveau service à partir de sa configuration. - * <p/> - * Note: le service n'est pas ouvert. - * - * @param config la configuration du service - * @return le service instancié non ouvert. - */ - S newService(C config); -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java b/observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java deleted file mode 100644 index a0ad902..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/ReplicationService.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.DecoratorService; -import fr.ird.observe.ObserveDAOHelper; -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.db.constants.DataSourceState; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.Trip; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.longline.TripLonglines; -import fr.ird.observe.entities.seine.TripSeineDAO; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.framework.TopiaSQLQuery; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.replication.TopiaReplicationService; -import org.nuiton.topia.replication.model.ReplicationModel; -import org.nuiton.util.StringUtil; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * Contrat du service de réplication d'entités. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ReplicationService { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReplicationService.class); - - protected DecoratorService decoratorService; - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveServiceHelper.getDecoratorService(); - } - return decoratorService; - } - - public void setDecoratorService(DecoratorService decoratorService) { - this.decoratorService = decoratorService; - } - - /** - * Duplication du référentiel depuis ce service vers le service donné. - * - * @param srcService le service source - * @param dstService le service destination - * @throws DataSourceException if pb - */ - public void replicateReferentiel(DataSource srcService, DataSource dstService) throws DataSourceException { - if (srcService == null) { - throw new NullPointerException("srcService can not be null"); - } - if (dstService == null) { - throw new NullPointerException("dstService can not be null"); - } - - srcService.checkState(DataSourceState.OPEN); - // le service peut-être en cours d'ouverture - dstService.checkState(DataSourceState.INIT, DataSourceState.OPEN); - if (srcService.equals(dstService)) { - throw new IllegalArgumentException( - "can not duplicate to the same service..."); - } - long t0 = System.nanoTime(); - - Date date = new Date(); - srcService.fireNewMessage( - t("observe.storage.message.replicate.referentiel.starting", date)); - - try { - - TopiaReplicationService service = - srcService.getTopiaService(TopiaReplicationService.class); - - ReplicationModel model = - service.prepareForAll(Entities.REFERENCE_ENTITIES); - - TopiaContext dstCtxt = dstService.getRootCtxt(); - service.doReplicate(model, dstCtxt); - - String delay = StringUtil.convertTime(t0, System.nanoTime()); - srcService.fireNewMessage( - t("observe.storage.message.replicate.referentiel.done", delay)); - } catch (Exception e) { - throw new DataSourceException(e, "replicateReferentiel"); - } - } - - /** - * Duplication de toutes les données observer de ce service vers le - * service donné. - * - * @param srcService le service source - * @param dstService le service destination - * @throws DataSourceException if pb - */ - public void replicateAllData(DataSource srcService, DataSource dstService) throws DataSourceException { - - if (dstService == null) { - throw new NullPointerException("dstService can not be null"); - } - srcService.checkState(DataSourceState.OPEN); - // le service peut-être en cours d'ouverture - dstService.checkState(DataSourceState.INIT, DataSourceState.OPEN); - - // recuperation des marees a repliquer - - String[] topiaIds = null; - - TopiaContext srcCtxt = null; - try { - srcCtxt = srcService.beginTransaction("replicateData"); - - TripSeineDAO srcTripDAO = ObserveDAOHelper.getTripSeineDAO(srcCtxt); - List<String> allIds = srcTripDAO.findAllIds(); - -// List<TripSeine> srcTripSeines = srcTripDAO.findAll(); - - if (CollectionUtils.isEmpty(allIds)) { - // aucune donnee a repliquer - srcService.fireNewMessage( - t("observe.storage.message.replicate.data.no.data")); - return; - } -// topiaIds = TopiaEntityHelper.getTopiaIdArray(srcTripSeines); - topiaIds = allIds.toArray(new String[allIds.size()]); - - } catch (TopiaException e) { - throw new DataSourceException(e, "replicateData"); - } finally { - if (srcCtxt != null) { - // rollback context since we do not want to keep any - // modification - try { - srcService.rollbackTransaction(srcCtxt, "replicateData"); - } finally { - srcService.closeTransaction(srcCtxt, "replicateData"); - } - } - } - - // replication des marees - replicateData(srcService, dstService, topiaIds); - - } - - /** - * Duplication de données observateur depuis ce service vers le service donné. - * - * @param srcService le service source - * @param dstService le service destination - * @param ids les ids des entités à répliquer - * @throws DataSourceException if pb - */ - public void replicateData(DataSource srcService, - DataSource dstService, - String... ids) throws DataSourceException { - if (srcService == null) { - throw new NullPointerException("srcService can not be null"); - } - if (dstService == null) { - throw new NullPointerException("dstService can not be null"); - } - - srcService.checkState(DataSourceState.OPEN); - // le service peut-être en cours d'ouverture - dstService.checkState(DataSourceState.INIT, DataSourceState.OPEN); - - if (srcService.equals(dstService)) { - throw new IllegalArgumentException( - "can not replcate to the same service..."); - } - - long t0 = System.nanoTime(); - - srcService.fireNewMessage( - t("observe.storage.message.replicate.entities.starting", new Date())); - - for (String id : ids) { - replicateOneData(srcService, dstService, id); - } - - srcService.fireNewMessage( - t("observe.storage.message.replicate.entities.done", StringUtil.convertTime(t0, System.nanoTime()))); - - } - - /** - * Duplication de l'unique donnée observateur depuis ce service vers le service donné. - * <p/> - * La duplication utilise une transaction dédiée afin de ne pas saturer le serveur - * et aussi une meilleure maitrise du rollback en cas d'une erreur. - * <p/> - * Voir http://forge.codelutin.com/issues/4837 - * - * @param srcService le service source - * @param dstService le service destination - * @param id les ids des entités à répliquer - * @throws DataSourceException if pb - */ - protected void replicateOneData(DataSource srcService, DataSource dstService, String id) throws DataSourceException { - - String dstLabel = dstService.getShortLabel(); - - TopiaReplicationService service = - srcService.getTopiaService(TopiaReplicationService.class); - - ReplicationModel model; - try { - model = service.prepare(Entities.DATA_ENTITIES, false, id); - } catch (TopiaException e) { - throw new DataSourceException(e, "replicateData"); - } - - // To fix missing tdr associations (see https://forge.codelutin.com/issues/6611) - List<Pair<String, String>> tdrAssociation = null; - - TopiaContext srcCtxt = srcService.beginTransaction("replicateData"); - try { - TopiaEntity e = srcCtxt.findByTopiaId(id); - String label = t(DecoratorService.getEntityLabel(e.getClass())) + " :: " + id; - srcService.fireNewMessage(t("observe.storage.message.replicate.data.entity", label, dstLabel)); - - if (e instanceof Trip && Entities.isLonglineId(id)) { - - // Grab tdr missing associations (see https://forge.codelutin.com/issues/6611) - if (log.isInfoEnabled()) { - log.info("Should keep SetLongline - Tdr association ids for: " + id); - } - - tdrAssociation = getTdrAssociationIds(srcCtxt, (TripLongline) e); - - } - } catch (TopiaException e) { - throw new DataSourceException(e, "replicateData"); - } finally { - srcService.closeTransaction(srcCtxt, "replicateData"); - } - - TopiaContext dstCtxt = dstService.beginTransaction("replicateData"); - try { - - // do the replicate - service.doReplicate(model, dstCtxt); - - // Apply back tdr missing associations (see https://forge.codelutin.com/issues/6611) - applyTdrAssociationFix(dstCtxt, tdrAssociation); - - // commit the result - dstService.commitTransaction(dstCtxt, "replicateData"); - - } catch (Exception e) { - dstService.rollbackTransaction(dstCtxt, "replicateData"); - throw new DataSourceException(e, "replicateData"); - } finally { - dstService.closeTransaction(dstCtxt, "replicateData"); - } - - } - - private void applyTdrAssociationFix(TopiaContext dstCtxt, List<Pair<String, String>> tdrAssociation) { - - String request = "\nUPDATE OBSERVE_LONGLINE.TDR SET SET = '%s' WHERE topiaid = '%s';"; - - StringBuilder builder = new StringBuilder(); - - if (CollectionUtils.isNotEmpty(tdrAssociation)) { - for (Pair<String, String> entry : tdrAssociation) { - builder.append(String.format(request, entry.getKey(), entry.getValue())); - } - } - - dstCtxt.executeSQL(builder.toString()); - - } - - private List<Pair<String, String>> getTdrAssociationIds(TopiaContext srcCtxt, TripLongline e) { - - List<Pair<String, String>> result = new ArrayList<Pair<String, String>>(); - - Set<String> setIds = TripLonglines.getSetIdsWithTdr(e); - - GetTdrIdsQuery query = new GetTdrIdsQuery(); - - for (String setId : setIds) { - - List<Pair<String, String>> multipleResult = query.execute((TopiaContextImplementor) srcCtxt, setId); - - if (log.isDebugEnabled()) { - log.debug("Found TDR associations: " + multipleResult); - } - result.addAll(multipleResult); - - } - - return result; - } - - - private static class GetTdrIdsQuery extends TopiaSQLQuery<Pair<String, String>> { - - private String setId; - - public List<Pair<String, String>> execute(TopiaContextImplementor tx, String setId) { - try { - - this.setId = setId; - return findMultipleResult(tx); - - } finally { - - this.setId = null; - - } - } - - @Override - protected PreparedStatement prepareQuery(Connection connection) throws SQLException { - String sql = "SELECT t.SET, t.topiaId " + - "FROM OBSERVE_LONGLINE.TDR t " + - "WHERE t.SET = ?"; - PreparedStatement ps = connection.prepareStatement(sql); - ps.setString(1, setId); - return ps; - } - - @Override - protected Pair<String, String> prepareResult(ResultSet set) throws SQLException { - Pair<String, String> result = - Pair.of(set.getString(1), set.getString(2)); - return result; - } - - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/VoidTopiaEntity.java b/observe-business/src/main/java/fr/ird/observe/db/VoidTopiaEntity.java deleted file mode 100644 index a89a51d..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/VoidTopiaEntity.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import org.nuiton.topia.persistence.TopiaEntity; - -/** - * A dummy contract to have a void entity type. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface VoidTopiaEntity extends TopiaEntity { - -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/constants/CommonDataSourceConfigParam.java b/observe-business/src/main/java/fr/ird/observe/db/constants/CommonDataSourceConfigParam.java deleted file mode 100644 index 5b6dbbf..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/constants/CommonDataSourceConfigParam.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceConfigParam; -import org.hibernate.cfg.Environment; -import org.nuiton.topia.migration.TopiaMigrationEngine; - -import java.util.Set; - -/** - * Les différents parametres communs a tout type de configuration. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum CommonDataSourceConfigParam implements DataSourceConfigParam { - - /** le lastName d'utilisateur pour se connecter à la base */ - LOGIN( - "login", - Environment.USER, - String.class - ), - /** le mot de passe de l'utilisateur pour se connecter à la base */ - PASSWORD( - "password", - Environment.PASS, - char[].class - ), - /** un drapeau pour voir les requetes sql lors de la migration. */ - SHOW_MIGRATION_SQL( - TopiaMigrationEngine.MIGRATION_SHOW_SQL, - Boolean.class - ), - /** un drapeau pour voir la progression des requetes sql lors de la migration. */ - SHOW_MIGRATION_PROGRESSION( - TopiaMigrationEngine.MIGRATION_SHOW_PROGRESSION, - Boolean.class - ), - /** un drapeau pour autoriser les migrations. */ - CAN_MIGRATE( - "migrate", - Boolean.class - ), - /** - * le type de création de la base. - * <p/> - * Si on veut juste utiliser une base sans opération de création, on - * n'utilise pas ce paramètre. - */ - CREATION_MODE("creationMode", CreationMode.class), - - /** - * le service de persistance à utiliser en mode création pour importer un - * référentiel. - * <p/> - * Cette donnée sera utilisée uniquement si le mode de création est : - * <p/> - * {@link CreationMode#IMPORT_LOCAL_STORAGE} - * ou {@link CreationMode#IMPORT_REMOTE_STORAGE}. - */ - IMPORT_CONFIG("importConfig", DataSourceConfig.class), - /** - * le service de persistance à utiliser en mode création pour importer - * des données. - */ - IMPORT_DATA_CONFIG("importDataConfig", DataSourceConfig.class), - - /** - * Les ids à importer (si {@code null} alors on import tout). - */ - IMPORT_DATA_IDS("importDataIds", Set.class); - - private final String mapName; - - private final String propertyName; - - private final Class<?> type; - - CommonDataSourceConfigParam(String name, Class<?> type) { - this(name, name, type); - } - - CommonDataSourceConfigParam(String propertyName, - String mapName, - Class<?> type) { - this.mapName = mapName; - this.propertyName = propertyName; - this.type = type; - } - - @Override - public String getMapName() { - return mapName; - } - - @Override - public String getPropertyName() { - return propertyName; - } - - @Override - public Class<?> getType() { - return type; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/constants/ConnexionStatus.java b/observe-business/src/main/java/fr/ird/observe/db/constants/ConnexionStatus.java deleted file mode 100644 index f87c840..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/constants/ConnexionStatus.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser l'état d'une connexion à un service de persistance. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum ConnexionStatus { - - /** lorsque la connexion n'as pas encore ete testee */ - UNTESTED( - n("observe.storage.connexionStatut.untested"), - n("observe.storage.connexionStatut.untested.description") - ), - /** lorsque le test de connexion a abouti */ - SUCCESS( - n("observe.storage.connexionStatut.success"), - n("observe.storage.connexionStatut.success.description") - ), - /** lorsque le test de connexion a echoue */ - FAILED( - n("observe.storage.connexionStatut.failed"), - n("observe.storage.connexionStatut.failed.description") - ); - - private final String label; - - private final String description; - - ConnexionStatus(String label, String description) { - this.label = label; - this.description = description; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/constants/CreationMode.java b/observe-business/src/main/java/fr/ird/observe/db/constants/CreationMode.java deleted file mode 100644 index f82178b..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/constants/CreationMode.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser comment créer une base locale. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum CreationMode { - - /** creer une nouvelle base locale vide */ - EMPTY( - n("observe.storage.creationMode.empty"), - n("observe.storage.creationMode.empty.description") - ), - /** creer une nouvelle base a partir du dump embarque */ - IMPORT_INTERNAL_DUMP( - n("observe.storage.creationMode.internalDump"), - n("observe.storage.creationMode.internalDump.description") - ), - /** creer une nouvelle base a partir d'un dump sur fs */ - IMPORT_EXTERNAL_DUMP( - n("observe.storage.creationMode.externalDump"), - n("observe.storage.creationMode.externalDump.description") - ), - /** - * creer une nouvelle base vide et importer le referentiel via une base - * locale. - */ - IMPORT_LOCAL_STORAGE( - n("observe.storage.creationMode.importLocalStorage"), - n("observe.storage.creationMode.importLocalStorage.description") - ), - /** - * creer une nouvelle base vide et importer le referentiel via une base - * distante. - */ - IMPORT_REMOTE_STORAGE( - n("observe.storage.creationMode.importRemoteStorage"), - n("observe.storage.creationMode.importRemoteStorage.description") - ); - - private final String label; - - private final String description; - - CreationMode(String label, String description) { - this.label = label; - this.description = description; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/constants/DataContextType.java b/observe-business/src/main/java/fr/ird/observe/db/constants/DataContextType.java deleted file mode 100644 index 592b4fc..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/constants/DataContextType.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import fr.ird.observe.db.DataContext; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.SetLongline; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TripSeine; - -/** - * Les types de données connues par le {@link DataContext}. - * <p/> - * Chaque constant permet de récupérer des données du context de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public enum DataContextType { - - Program(Program.class, DataContext.PROPERTY_OPEN_PROGRAM) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenProgram(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenProgramId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenProgramId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedProgramId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedProgramId(id); - } - }, - - TripSeine(TripSeine.class, DataContext.PROPERTY_OPEN_TRIP) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenTripSeine(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenTripSeineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenTripId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedTripSeineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedTripId(id); - } - }, - - TripLongline(TripLongline.class, DataContext.PROPERTY_OPEN_TRIP) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenTripLongline(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenTripLonglineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenTripId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedTripLonglineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedTripId(id); - } - }, - - Route(Route.class, DataContext.PROPERTY_OPEN_ROUTE) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenRoute(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenRouteId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenRouteId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedRouteId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedRouteId(id); - } - }, - - ActivitySeine(ActivitySeine.class, DataContext.PROPERTY_OPEN_ACTIVITY) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenActivityLongline(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenActivitySeineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenActivityId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedActivitySeineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedActivityId(id); - } - }, - - ActivityLongline(ActivityLongline.class, DataContext.PROPERTY_OPEN_ACTIVITY) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenActivityLongline(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenActivityLonglineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenActivityId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedActivityLonglineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedActivityId(id); - } - }, - - SetSeine(SetSeine.class, DataContext.PROPERTY_OPEN_SET) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenSetSeine(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenSetSeineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenSetId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedSetSeineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedSetId(id); - } - }, - - SetLongline(SetLongline.class, DataContext.PROPERTY_OPEN_SET) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenSetLongline(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenSetLonglineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenSetId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedSetLonglineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedSetId(id); - } - }, - - FloatingObject(FloatingObject.class, null) { - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedFloatingObjectId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedFloatingObjectId(id); - } - }; - - private final Class<?> type; - - private final String openProperty; - - DataContextType(Class<?> type, String openProperty) { - this.type = type; - this.openProperty = openProperty; - } - - public boolean acceptType(Class<?> type) { - return type.equals(getType()); - } - - public boolean acceptId0(String id) { - return id.startsWith(getType().getName()); - } - - public Class<?> getType() { - return type; - } - - public String getOpenProperty() { - return openProperty; - } - - public boolean canOpen() { - return openProperty != null; - } - - public boolean isOpen(DataContext context) { - return false; - } - - public String getOpenId(DataContext context) { - return null; - } - - public abstract String getSelectedId(DataContext context); - - public abstract void setSelectedId(DataContext context, String id); - - public static DataContextType acceptId(String s) { - DataContextType result = null; - for (DataContextType type : DataContextType.values()) { - if (s.startsWith(type.getType().getName())) { - result = type; - break; - } - } - return result; - } - - public void setOpenId(DataContext dataContext, String id) { - // rien a faire par defaut - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/constants/DataPolicy.java b/observe-business/src/main/java/fr/ird/observe/db/constants/DataPolicy.java deleted file mode 100644 index 6cd2673..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/constants/DataPolicy.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser les droits de lecture, ecriture sur les données d'un - * service de persistance. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum DataPolicy { - - /** pour lire le référentiel */ - READ_REFERENTIEL( - n("observe.storage.dataPolicy.readReferentiel"), - n("observe.storage.dataPolicy.readReferentiel.description") - ), - /** pour lire les données observer */ - READ_DATA( - n("observe.storage.dataPolicy.readData"), - n("observe.storage.dataPolicy.readData.description") - ), - /** pour modifier le référentiel */ - WRITE_REFERENTIEL( - n("observe.storage.dataPolicy.writeReferentiel"), - n("observe.storage.dataPolicy.writeReferentiel.description") - ), - /** pour modifier les données observer */ - WRITE_DATA( - n("observe.storage.dataPolicy.writeData"), - n("observe.storage.dataPolicy.writeData.description") - ); - - private final String label; - - private final String description; - - DataPolicy(String label, String description) { - this.label = label; - this.description = description; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/constants/DataSourceState.java b/observe-business/src/main/java/fr/ird/observe/db/constants/DataSourceState.java deleted file mode 100644 index 46bb8c6..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/constants/DataSourceState.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -/** - * Pour qualifier l'état d'un storageService. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum DataSourceState { - - /** avant l'intialisation */ - NULL, - /** apres l'initialisation */ - INIT, - /** apres l'ouverture */ - OPEN, - /** apres la fermeture */ - CLOSED -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/constants/DbMode.java b/observe-business/src/main/java/fr/ird/observe/db/constants/DbMode.java deleted file mode 100644 index 23053b9..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/constants/DbMode.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser le type de connexion requis. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum DbMode { - /** Pour utiliser une base locale */ - USE_LOCAL( - n("observe.storage.dbMode.useLocal"), - n("observe.storage.dbMode.useLocal.description") - ), - /** Pour creer une base locale */ - CREATE_LOCAL( - n("observe.storage.dbMode.createLocal"), - n("observe.storage.dbMode.createLocal.description") - ), - /** Pour utiliser une base distante */ - USE_REMOTE( - n("observe.storage.dbMode.useRemote"), - n("observe.storage.dbMode.useRemote.description") - ); - - private final String label; - - private final String description; - - DbMode(String label, String description) { - this.label = label; - this.description = description; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceEvent.java b/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceEvent.java deleted file mode 100644 index 5ed615c..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.event; - -import fr.ird.observe.db.DataSource; - -import java.util.EventObject; - -/** - * Les évènements produits lors des changements du cycle de vie d'une source - * de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataSourceEvent extends EventObject { - - private static final long serialVersionUID = 1L; - - /** an extra message to be used when using {@link DataSourceListener#onNewMessage(DataSourceEvent)}. */ - protected String message; - - public enum MessageLevel { - FATAL, - ERROR, - WARN, - INFO, - DEBUG, - TRACE - } - - protected MessageLevel messageLevel; - - /** - * Constructs a prototypical Event. - * - * @param source The object on which the Event initially occurred. - * @throws IllegalArgumentException if source is null. - */ - public DataSourceEvent(DataSource source) { - super(source); - } - - public DataSourceEvent(DataSource source, - String message, - MessageLevel messageLevel) { - super(source); - this.message = message; - this.messageLevel = messageLevel; - } - - @Override - public DataSource getSource() { - return (DataSource) super.getSource(); - } - - public String getMessage() { - return message; - } - - public MessageLevel getMessageLevel() { - return messageLevel; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceListener.java b/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceListener.java deleted file mode 100644 index bbbc9f4..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceListener.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.event; - -import fr.ird.observe.db.DataSource; - -import java.util.EventListener; - -/** - * Le contrat d'un listener sur une source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface DataSourceListener extends EventListener { - - - /** - * Déclanché avant l'ouverture d'un service (i.e au debut de la méthode - * {@link DataSource#doOpen()}). - * - * @param event l'evenement de pre-ouverture - */ - void onOpening(DataSourceEvent event); - - /** - * Déclanché apres une ouverture d'un service (i.e à la fin de la méthode - * {@link DataSource#doOpen()}). - * - * @param event l'evenement d'ouverture - */ - void onOpened(DataSourceEvent event); - - /** - * Déclanché avant la fermeture d'un service (i.e au avant la méthode {@link - * DataSource#doClose(boolean)}). - * - * @param event l'evenement de pre-fermeture - */ - void onClosing(DataSourceEvent event); - - /** - * Déclanché apres la fermeture d'un service (i.e apres de la méthode {@link - * DataSource#doClose(boolean)}). - * - * @param event l'evenement de fermeture - */ - void onClosed(DataSourceEvent event); - - /** - * Déclanché pour envoyer un nouveau message. - * - * @param event l'evenement de message - */ - void onNewMessage(DataSourceEvent event); -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceListenerAdapter.java b/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceListenerAdapter.java deleted file mode 100644 index e23dd74..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/event/DataSourceListenerAdapter.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.event; - -/** - * Un adapteur de {@link DataSourceListener}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataSourceListenerAdapter implements DataSourceListener { - - @Override - public void onOpening(DataSourceEvent event) { - // ne fait rien - } - - @Override - public void onOpened(DataSourceEvent event) { - // ne fait rien - } - - @Override - public void onClosing(DataSourceEvent event) { - // ne fait rien - } - - @Override - public void onClosed(DataSourceEvent event) { - // ne fait rien - } - - @Override - public void onNewMessage(DataSourceEvent event) { - // ne fait rien - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSource.java b/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSource.java deleted file mode 100644 index 051b6ce..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSource.java +++ /dev/null @@ -1,863 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import com.google.common.base.Preconditions; -import com.google.common.base.Supplier; -import fr.ird.observe.ObserveEntityEnum; -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.db.ReplicationService; -import fr.ird.observe.db.constants.CommonDataSourceConfigParam; -import fr.ird.observe.db.constants.DataSourceState; -import fr.ird.observe.db.event.DataSourceEvent; -import fr.ird.observe.db.event.DataSourceListener; -import fr.ird.observe.entities.OpenableEntity; -import fr.ird.observe.entities.OpenableEntityDAOImpl; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.SetLongline; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TripSeine; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.SessionFactory; -import org.hibernate.cfg.Environment; -import org.hibernate.stat.Statistics; -import org.nuiton.config.ApplicationConfig; -import org.nuiton.decorator.Decorator; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; - -import org.nuiton.topia.TopiaNotFoundException; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.framework.TopiaService; -import org.nuiton.topia.migration.TopiaMigrationEngine; -import org.nuiton.topia.migration.TopiaMigrationService; -import org.nuiton.topia.migration.mappings.TMSVersion; -import org.nuiton.topia.migration.mappings.TMSVersionDAO; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.version.Version; - -import javax.management.MBeanServer; -import javax.management.MXBean; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.swing.event.EventListenerList; -import java.lang.management.ManagementFactory; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; - -import static fr.ird.observe.db.event.DataSourceEvent.MessageLevel; -import static org.nuiton.i18n.I18n.t; - -//import org.hibernate.jmx.StatisticsService; - -/** - * L'implantation abstraite d'un service de persistance. - * <p/> - * Tous les services implantés héritent de ce service. - * <p/> - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class AbstractDataSource implements DataSource { - - /** Logger */ - private static final Log log = - LogFactory.getLog(AbstractDataSource.class); - - /** l'état interne du service */ - protected DataSourceState state; - - /** le contexte principale sur la base */ - protected TopiaContextImplementor rootCtxt; - - /** la configuration du service */ - protected final DataSourceConfig config; - - /** le conteneur de listeners */ - protected final EventListenerList listenerList; - - protected ReplicationService replicationService; - - protected AbstractDataSource(DataSourceConfig config) { - state = DataSourceState.NULL; - listenerList = new EventListenerList(); - this.config = config; - } - - @Override - public void init() { - - checkState(DataSourceState.NULL); - - config.init(); - - state = DataSourceState.INIT; - } - - @Override - public void doOpen() throws DataSourceException { - fireNewMessage(t("observe.storage.message.opening", getLabel())); - beforeOpen(); - fireOpening(); - open(); - checkState(DataSourceState.OPEN); - fireNewMessage(t("observe.storage.message.opened", getLabel())); - fireOpened(); - } - - @Override - public void doClose(boolean destroy) throws DataSourceException { - if (state == DataSourceState.CLOSED) { - // already closed - if (log.isWarnEnabled()) { - log.warn("service " + this + " was already closed."); - } - return; - } - fireNewMessage(t("observe.storage.message.closing", getLabel())); - beforeClose(destroy); - fireClosing(); - close(destroy); - checkState(DataSourceState.CLOSED); - fireNewMessage(t("observe.storage.message.closed", getLabel())); - fireClosed(); - // once really closed, clean listeners - removeDataSourceListeners(); - } - - @Override - public <S extends TopiaService> S getTopiaService(Class<S> serviceClass) { - checkState(DataSourceState.OPEN); - try { - S service; - service = getRootCtxt().getService(serviceClass); - return service; - } catch (TopiaNotFoundException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - @Override - public TopiaContext getRootCtxt() { - return rootCtxt; - } - - @Override - public boolean isOpen() { - return DataSourceState.OPEN == state; - } - - @Override - public boolean wasClosed() { - return DataSourceState.CLOSED == state; - } - - @Override - public String getLabel() { - return config.getLabel(); - } - - @Override - public String getShortLabel() { - return config.getShortLabel(); - } - - @Override - public DataSourceConfig getConfig() { - return config; - } - - @Override - public boolean canReadData() { - return config.isCanReadData(); - } - - @Override - public boolean canReadReferentiel() { - return config.isCanReadReferentiel(); - } - - @Override - public boolean canWriteData() { - return config.isCanWriteData(); - } - - @Override - public boolean canWriteReferentiel() { - return config.isCanWriteReferentiel(); - } - - @Override - public ReplicationService getReplicationService() { - if (replicationService == null) { - replicationService = new ReplicationService(); - } - return replicationService; - } - - @Override - public void checkState(DataSourceState... state) - throws IllegalStateException { - for (DataSourceState s : state) { - if (s == this.state) { - return; - } - } - throw new IllegalStateException( - "should be in one of thoses states " + - Arrays.toString(state) + ", but was " + this.state); - - } - - @Override - public <P extends TopiaEntity> TopiaDAO<P> getDAO(TopiaContext tx, Class<P> entityType) { - - TopiaContextImplementor ci = (TopiaContextImplementor) tx; - TopiaDAO<P> dao = ci.getDAO(entityType); - return dao; - } - - @SuppressWarnings({"unchecked"}) - @Override - public <P extends TopiaEntity> TopiaDAO<P> getDAO(TopiaContext tx, P entity) { - ObserveEntityEnum constant = ObserveEntityEnum.valueOf(entity); - - return getDAO(tx, (Class<P>) constant.getContract()); - } - - @Override - public <E extends OpenableEntity & TopiaEntity> E getOpen(TopiaContext tx, Class<E> klass) throws DataSourceException { - if (!canReadData()) { - if (log.isInfoEnabled()) { - log.info("Can not read data!"); - } - return null; - } - try { - - TopiaDAO<E> dao = getDAO(tx, klass); - E result = (E) ((OpenableEntityDAOImpl) dao).findByOpen(true); - return result; - - } catch (Exception e) { - throw new DataSourceException(e, "getOpen"); - } - } - - @Override - public String[] getOpenIds(TopiaContext tx) throws DataSourceException { - - List<String> result = new ArrayList<String>(); - - { - TripSeine trip = getOpen(tx, TripSeine.class); - if (trip != null) { - if (trip.getProgram() != null) { - result.add(trip.getProgram().getTopiaId()); - } - result.add(trip.getTopiaId()); - Route route = getOpen(tx, Route.class); - if (route != null) { - result.add(route.getTopiaId()); - ActivitySeine activity = getOpen(tx, ActivitySeine.class); - if (activity != null) { - result.add(activity.getTopiaId()); - SetSeine set = activity.getSetSeine(); - if (set != null) { - result.add(set.getTopiaId()); - } - } - } - } - } - - { - TripLongline trip = getOpen(tx, TripLongline.class); - if (trip != null) { - if (trip.getProgram() != null) { - result.add(trip.getProgram().getTopiaId()); - } - result.add(trip.getTopiaId()); - ActivityLongline activity = getOpen(tx, ActivityLongline.class); - if (activity != null) { - result.add(activity.getTopiaId()); - SetLongline set = activity.getSetLongline(); - if (set != null) { - result.add(set.getTopiaId()); - } - } - } - } - return result.toArray(new String[result.size()]); - } - - @Override - public void addDataSourceListener(DataSourceListener listener) { - listenerList.add(DataSourceListener.class, listener); - } - - @Override - public boolean containsDataSourceListener(DataSourceListener listener) { - DataSourceListener[] listeners = getDataSourceListeners(); - for (DataSourceListener l : listeners) { - if (l.equals(listener)) { - return true; - } - } - return false; - } - - @Override - public DataSourceListener[] getDataSourceListeners() { - return listenerList.getListeners(DataSourceListener.class); - } - - @Override - public void removeDataSourceListener(DataSourceListener listener) { - listenerList.remove(DataSourceListener.class, listener); - } - - public TopiaContext beginTransaction(String methodName) throws DataSourceException { - try { - TopiaContext tx = getRootCtxt().beginTransaction(); - return tx; - } catch (Exception ex) { - throw new DataSourceException(ex, methodName); - } - } - - public void closeTransaction(TopiaContext tx, String methodName) throws DataSourceException { - try { - tx.closeContext(); - } catch (Exception ex) { - throw new DataSourceException(ex, methodName); - } - } - - public void rollbackTransaction(TopiaContext tx, String methodName) throws DataSourceException { - try { - tx.rollbackTransaction(); - } catch (Exception ex) { - throw new DataSourceException(ex, methodName); - } - } - - public void commitTransaction(TopiaContext tx, String methodName) throws DataSourceException { - try { - tx.commitTransaction(); - } catch (Exception ex) { - throw new DataSourceException(ex, methodName); - } - } - - protected void beforeOpen() throws DataSourceException { - checkState(DataSourceState.INIT); - if (ObserveServiceHelper.isUseJMX()) { - - if (log.isInfoEnabled()) { - log.info("Add jmx support for " + getLabel()); - } - // add jmx support - getConfig().getDbConfig().setProperty( - Environment.GENERATE_STATISTICS, - String.valueOf(true)); - } - } - - protected void beforeClose(boolean destroy) throws DataSourceException { - if (ObserveServiceHelper.isUseJMX()) { - dettachHibernateMBean(); - } - } - - /** - * Open the storage service (i.e open a connection to db). - * <p/> - * At the end of this method the storage's state must pass to {@link - * DataSourceState#OPEN} if everything is ok. - * - * @throws DataSourceException if pb - */ - protected void open() throws DataSourceException { - try { - Properties p = getConfigForTopia(); - - // has using C3P0 pool, must have a safe strict properties - // (everything is string and can not accept to have a null value for - // a given key) - Properties safeP = new Properties(); - for (String key : p.stringPropertyNames()) { - String property = p.getProperty(key); - if (property != null) { - safeP.setProperty(key, property); - } - } - rootCtxt = - (TopiaContextImplementor) TopiaContextFactory.getContext(safeP); - rootCtxt.setUseFlushMode(false); - config.detectPolicy(); - - if (ObserveServiceHelper.isUseJMX()) { - createHibernateMBean(); - } - state = DataSourceState.OPEN; - } catch (TopiaException ex) { - throw new DataSourceException(ex, "open"); - } - } - - @Override - public String decorateEntity(TopiaContext tx, String id, Decorator<?> decorator) throws DataSourceException { - checkState(DataSourceState.OPEN); - - Preconditions.checkNotNull(id, "No id given!"); - Preconditions.checkNotNull(decorator, "No decorator for id " + id); - - String txName = "decorateEntity :: " + id; - boolean createTX = tx == null; - if (createTX) { - tx = beginTransaction(txName); - } - try { - - TopiaEntity entity = tx.findByTopiaId(id); - Preconditions.checkNotNull(entity, "Could not find entity " + id); - - return decorator.toString(entity); - - } catch (TopiaException ex) { - throw new DataSourceException("Could not load entity " + id, ex, txName); - } finally { - if (createTX) { - closeTransaction(tx, txName); - } - } - } - - @Override - public <E extends TopiaEntity> List<E> loadDecoratedEntities(TopiaContext tx, - Class<E> entityClass, - Decorator<E> decorator) throws DataSourceException { - checkState(DataSourceState.OPEN); - String txName = "loadDecoratedEntities :: " + entityClass.getName(); - boolean createTX = tx == null; - if (createTX) { - tx = beginTransaction(txName); - } - try { - TopiaDAO<E> dao = getDAO(tx, entityClass); - List<E> result = dao.findAll(); - - for (E e : result) { - decorator.toString(e); - } - - return result; - } catch (TopiaException e) { - throw new DataSourceException("Can not obtain list of " + entityClass, e, txName); - } finally { - if (createTX) { - closeTransaction(tx, txName); - } - } - } - - @Override - public Version getDbVersion() throws DataSourceException { - - checkState(DataSourceState.OPEN); - - Version v = getDbVersion0(); - return v; - - } - - protected Version getDbVersion0() throws DataSourceException { - - Version v = null; - TopiaContext tx = null; - try { - - tx = beginTransaction("getDbVersion"); - - if (rootCtxt.isSchemaExist(TMSVersion.class)) { - - TMSVersion tmsVersion = TMSVersionDAO.get(tx); - if (tmsVersion != null) { - v = tmsVersion.toVersion(); - } - } else { - // this is only for test purpose... should disapear soon - v = TMSVersionDAO.getVersion(tx, TMSVersionDAO.LEGACY_TABLE_NAME); - } - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error("could not retreave dbVersion for reason " + - ex.getMessage(), ex); - } - } finally { - if (tx != null) { - rollbackTransaction(tx, "getDbVersion"); - closeTransaction(tx, "getDbVersion"); - } - } - return v; - } - - @Override - public Properties getConfigForTopia() { - Properties p = new Properties(); - p.putAll(config.getDbConfig()); - p.put(CommonDataSourceConfigParam.PASSWORD.getMapName() - , new String(config.getPassword())); - p.put(CommonDataSourceConfigParam.SHOW_MIGRATION_SQL.getMapName(), - String.valueOf(config.isShowMigrationSql())); - p.put(CommonDataSourceConfigParam.SHOW_MIGRATION_PROGRESSION.getMapName(), - String.valueOf(config.isShowMigrationProgression())); - return p; - } - - @Override - public void fireNewMessage(String message) { - DataSourceEvent evt = new DataSourceEvent(this, message, MessageLevel.INFO); - for (DataSourceListener listener : getDataSourceListeners()) { - listener.onNewMessage(evt); - } - } - - @Override - public void fireNewMessage(String message, MessageLevel level) { - DataSourceEvent evt = new DataSourceEvent(this, message, MessageLevel.INFO); - for (DataSourceListener listener : getDataSourceListeners()) { - listener.onNewMessage(evt); - } - } - - @Override - public <E> E findByTopiaId(TopiaContext tx, String entityId) { - return (E) tx.findByTopiaId(entityId); - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append(t(getLabel())); - buffer.append("\n").append(config.toString()); - if (isOpen()) { - try { - buffer.append("\n\n"); - buffer.append(t("observe.storage.db.version")); - buffer.append("\n - "); - Version v = getDbVersion(); - if (v == null) { - buffer.append(t("observe.storage.unversionned.db")); - } else { - buffer.append("v ").append(v.getVersion()); - } - } catch (DataSourceException ex) { - // ignore it - } - } - return buffer.toString(); - } - - /** - * Close the underlying db, and destroy it if the parameter is at true. - * - * @param destroy {@code true} if the underlying db must be destroyed - * @throws DataSourceException if db pb - */ - protected void close(boolean destroy) throws DataSourceException { - try { - if (destroy) { - rootCtxt.clear(true); - } else { - rootCtxt.closeContext(); - } - } catch (Exception e) { - throw new DataSourceException(e, "close"); - } finally { - state = DataSourceState.CLOSED; - } - } - - protected void removeDataSourceListeners() { - // remove all listeners - for (DataSourceListener listener : getDataSourceListeners()) { - if (log.isInfoEnabled()) { - log.info("removing listener " + listener); - } - removeDataSourceListener(listener); - } - } - - protected void fireOpening() { - DataSourceEvent evt = new DataSourceEvent(this); - for (DataSourceListener listener : getDataSourceListeners()) { - listener.onOpening(evt); - } - } - - protected void fireOpened() { - DataSourceEvent evt = new DataSourceEvent(this); - for (DataSourceListener listener : getDataSourceListeners()) { - listener.onOpened(evt); - } - } - - protected void fireClosing() { - DataSourceEvent evt = new DataSourceEvent(this); - for (DataSourceListener listener : getDataSourceListeners()) { - listener.onClosing(evt); - } - } - - protected void fireClosed() { - DataSourceEvent evt = new DataSourceEvent(this); - for (DataSourceListener listener : getDataSourceListeners()) { - listener.onClosed(evt); - } - } - - protected void doMigrateSchema() throws DataSourceException { - - fireNewMessage(t("observe.storage.message.launch.migration", getLabel())); - - try { - // on lance la migration du schema - TopiaMigrationEngine service = (TopiaMigrationEngine) - rootCtxt.getService(TopiaMigrationService.class); - service.doMigrateSchema(); - } catch (Exception ex) { - throw new DataSourceException(ex, "doMigrate"); - } - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - - // remove all listeners if any - removeDataSourceListeners(); - } - - protected abstract void createSchema(String schemaName) throws TopiaException; - - protected void createSchemaOrUpdate(boolean mustCreateSchema, boolean canMigrate) throws Exception { - if (mustCreateSchema) { - - fireNewMessage(t("observe.storage.message.create.schema", getLabel())); - - // create schemas before all - createSchema("OBSERVE_COMMON"); - createSchema("OBSERVE_SEINE"); - createSchema("OBSERVE_LONGLINE"); - - // update works better than create... - rootCtxt.updateSchema(); - } else if (canMigrate) { - - // lancement de la migration - doMigrateSchema(); - } - - // Check database version - Version dbVersion = getDbVersion0(); - - Supplier<ApplicationConfig> applicationConfigSupplier = AbstractDataSourceMigration.getApplicationConfigSupplier(); - Preconditions.checkNotNull(applicationConfigSupplier); - Version applicationVersion = applicationConfigSupplier.get().getOptionAsVersion(AbstractDataSourceMigration.DB_VERSION); - - if (dbVersion != null && applicationVersion.before(dbVersion)) { - - String message = t("observe.storage.database.higher.than.application", dbVersion, applicationVersion); - throw new DataSourceException(message, "createSchemaOrUpdate"); - - } - - } - - protected final void importReferentiel(DataSourceConfig importConfig) throws Exception { - - if (importConfig == null) { - throw new NullPointerException("importConfig parameter can not be null in importReferentiel"); - } - - // chemit 2010/09/21 La base d'import ne peut jamais être créée - importConfig.setCreationMode(null); - - DataSource importService = null; - - if (importConfig instanceof H2DataSourceConfig) { - importService = DataSourceFactory.newService((H2DataSourceConfig) importConfig); - } - - if (importConfig instanceof PGDataSourceConfig) { - importService = DataSourceFactory.newService((PGDataSourceConfig) importConfig); - } - - if (importService == null) { - - throw new IllegalStateException("No importService instanciated"); - } - - try { - fireNewMessage(t("observe.storage.message.import.referentiel.from", importService.getLabel())); - fireNewMessage(t("observe.storage.message.import.referentiel.to", getLabel())); - importService.doOpen(); - - ReplicationService service = getReplicationService(); - service.replicateReferentiel(importService, this); - } catch (Exception ex) { - if (log.isErrorEnabled()) { - log.error(t("observe.storage.error.import.referentiel", ex.getMessage()), ex); - } - throw ex; - } finally { - importService.doClose(false); - fireNewMessage(t("observe.storage.message.import.referentiel.done")); - } - } - - - protected final void importData(DataSourceConfig importConfig, Collection<String> dataIds) throws Exception { - - if (importConfig == null) { - throw new NullPointerException("importConfig parameter can not be null in importData"); - } - - // chemit 2010/09/21 La base d'import ne peut jamais être créée - importConfig.setCreationMode(null); - - DataSource importService = DataSourceFactory.newService(importConfig); - - if (importService == null) { - - throw new IllegalStateException("No importService instanciated"); - } - - try { - fireNewMessage(t("observe.storage.message.import.data.from", importService.getLabel())); - fireNewMessage(t("observe.storage.message.import.data.to", getLabel())); - importService.doOpen(); - - ReplicationService service = getReplicationService(); - - if (dataIds == null) { - - // means import all datas - service.replicateAllData(importService, this); - - } else { - - service.replicateData(importService, this, dataIds.toArray(new String[dataIds.size()])); - } - - } catch (Exception ex) { - if (log.isErrorEnabled()) { - log.error(t("observe.storage.error.import.referentiel", ex.getMessage()), ex); - } - throw ex; - } finally { - importService.doClose(false); - fireNewMessage(t("observe.storage.message.import.referentiel.done")); - } - } - - @MXBean - public interface StatisticsMXBean extends Statistics { - } - - protected void createHibernateMBean() { - try { - ObjectName on = createMBean(); - if (log.isInfoEnabled()) { - log.info("attach MBean " + on); - } - MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - SessionFactory sessionFactory = ((TopiaContextImplementor) getRootCtxt()).getHibernateFactory(); - - final Statistics stats = sessionFactory.getStatistics(); - stats.setStatisticsEnabled(true); - Object statisticsMBean = Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{StatisticsMXBean.class}, new InvocationHandler() { - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return method.invoke(stats, args); - } - }); - - server.registerMBean(statisticsMBean, on); - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("Could not attach hibernate session to JMX...", e); - } - } - } - - protected void dettachHibernateMBean() { - // suppression MBean sur la session hibernate - try { - MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - ObjectName on = createMBean(); - if (log.isInfoEnabled()) { - log.info("dettach MBean " + on); - } - // UnRegister the Mbean on the server - server.unregisterMBean(on); - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("Could not dettach hibernate session from JMX...", e); - } - } - } - - @SuppressWarnings({"UseOfObsoleteCollectionType"}) - protected ObjectName createMBean() throws MalformedObjectNameException { - Hashtable<String, String> tb = new Hashtable<String, String>(); - tb.put("type", "statistics"); - String name = getLabel(); - tb.put("sessionFactory", name.replaceAll(":", "_")); - // MBean object name - ObjectName on = new ObjectName("hibernate", tb); - return on; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSourceConfig.java b/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSourceConfig.java deleted file mode 100644 index 900d673..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSourceConfig.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceConfigParam; -import fr.ird.observe.db.constants.CommonDataSourceConfigParam; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DataPolicy; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.EnumSet; -import java.util.Properties; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * L'implantation abstraite de base d'une configuration de service. - * - * @author Tony Chemit - chemit@codelutin.com - * @see DataSourceConfig - * @since 1.0 - */ -public abstract class AbstractDataSourceConfig implements DataSourceConfig { - - /** Logger */ - private static final Log log = - LogFactory.getLog(AbstractDataSourceConfig.class); - - /** la configuration de connexion à la base */ - protected Properties dbConfig; - - /** le label court de persistance */ - protected String shortLabel; - - /** - * un drapeau pour savoir si on utilise un cache sur les entites du - * référentiel. - */ - protected boolean useCache; - - /** les droits en lecture-écriture sur les données */ - protected EnumSet<DataPolicy> policy; - - protected AbstractDataSourceConfig(String label) { - this(label, null); - } - - protected AbstractDataSourceConfig(String shortLabel, Properties dbConfig) { - if (shortLabel == null) { - throw new NullPointerException("shortLabel can not be null"); - } - this.shortLabel = shortLabel; - this.dbConfig = dbConfig == null ? new Properties() : dbConfig; - // par defaut aucun droit de lecture-ecriture - policy = EnumSet.noneOf(DataPolicy.class); - } - - @Override - public Properties getDbConfig() { - return dbConfig; - } - - @Override - public boolean isUseCache() { - return useCache; - } - - @Override - public String getShortLabel() { - return t(shortLabel); - } - - @Override - public EnumSet<DataPolicy> getPolicy() { - return policy; - } - - @Override - public void setShortLabel(String shortLabel) { - this.shortLabel = shortLabel; - } - - @Override - public void setUseCache(boolean useCache) { - this.useCache = useCache; - } - - @Override - public String getLogin() { - return get(CommonDataSourceConfigParam.LOGIN, String.class); - } - - @Override - public void setLogin(String login) { - set(CommonDataSourceConfigParam.LOGIN, login); - } - - @Override - public char[] getPassword() { - return get(CommonDataSourceConfigParam.PASSWORD, char[].class); - } - - @Override - public void setPassword(char[] password) { - set(CommonDataSourceConfigParam.PASSWORD, password); - } - - @Override - public boolean isCanMigrate() { - Boolean result = get(CommonDataSourceConfigParam.CAN_MIGRATE, - Boolean.class); - return result != null && result; - } - - @Override - public boolean isShowMigrationSql() { - Boolean result = get(CommonDataSourceConfigParam.SHOW_MIGRATION_SQL, - Boolean.class); - return result != null && result; - } - - @Override - public boolean isShowMigrationProgression() { - Boolean result = get( - CommonDataSourceConfigParam.SHOW_MIGRATION_PROGRESSION, - Boolean.class); - return result != null && result; - } - - @Override - public boolean isCanReadData() { - return getPolicy().contains(DataPolicy.READ_DATA); - } - - @Override - public boolean isCanReadReferentiel() { - return getPolicy().contains(DataPolicy.READ_REFERENTIEL); - } - - @Override - public boolean isCanWriteData() { - return getPolicy().contains(DataPolicy.WRITE_DATA); - } - - @Override - public boolean isCanWriteReferentiel() { - return getPolicy().contains(DataPolicy.WRITE_REFERENTIEL); - } - - @Override - public void setShowMigrationSql(boolean showMigrationSql) { - set(CommonDataSourceConfigParam.SHOW_MIGRATION_SQL, showMigrationSql); - } - - @Override - public void setShowMigrationProgression(boolean showMigrationProgression) { - set(CommonDataSourceConfigParam.SHOW_MIGRATION_PROGRESSION, - showMigrationProgression); - } - - @Override - public void setCanMigrate(boolean canMigrate) { - set(CommonDataSourceConfigParam.CAN_MIGRATE, canMigrate); - } - - @Override - public CreationMode getCreationMode() { - return get(CommonDataSourceConfigParam.CREATION_MODE, CreationMode.class); - } - - @Override - public void setCreationMode(CreationMode creationMode) { - set(CommonDataSourceConfigParam.CREATION_MODE, creationMode); - } - - @Override - public DataSourceConfig getImportConfig() { - return get(CommonDataSourceConfigParam.IMPORT_CONFIG, DataSourceConfig.class); - } - - @Override - public void setImportConfig(DataSourceConfig importConfig) { - set(CommonDataSourceConfigParam.IMPORT_CONFIG, importConfig); - } - - @Override - public DataSourceConfig getImportDataConfig() { - return get(CommonDataSourceConfigParam.IMPORT_DATA_CONFIG, DataSourceConfig.class); - } - - @Override - public void setImportDataConfig(DataSourceConfig importDataConfig) { - set(CommonDataSourceConfigParam.IMPORT_DATA_CONFIG, importDataConfig); - } - - @Override - public Set<String> getImportDataIds() { - return get(CommonDataSourceConfigParam.IMPORT_DATA_IDS, Set.class); - } - - @Override - public void setImportDataIds(Set<String> importDataIds) { - set(CommonDataSourceConfigParam.IMPORT_DATA_IDS, importDataIds); - } - - public boolean hasImportReferentielConfig() { - return getImportConfig() != null; - } - -// @Override -// public boolean hasH2ImportConfig() { -// return getImportConfig() != null && -// getImportConfig() instanceof H2DataSourceConfig; -// } -// -// @Override -// public boolean hasPGImportConfig() { -// return getImportConfig() != null && -// getImportConfig() instanceof PGDataSourceConfig; -// } - - - @Override - public boolean hasImportDataConfig() { - boolean hasImport = getImportDataConfig() != null; - if (hasImport) { - - // check also if some ids were selected - // if null then import all data - hasImport = getImportDataIds() == null || !getImportDataIds().isEmpty(); - } - return hasImport; - } - -// @Override -// public H2DataSourceConfig getH2ImportConfig() { -// DataSourceConfig importConfig = getImportConfig(); -// if (importConfig != null && -// !(importConfig instanceof H2DataSourceConfig)) { -// throw new ClassCastException("can not cast " + importConfig + -// " to " + H2DataSourceConfig.class); -// } -// return (H2DataSourceConfig) importConfig; -// } - -// @Override -// public PGDataSourceConfig getPGImportConfig() { -// DataSourceConfig importConfig = getImportConfig(); -// if (importConfig != null && -// !(importConfig instanceof PGDataSourceConfig)) { -// throw new ClassCastException("can not cast " + importConfig + -// " to " + PGDataSourceConfig.class); -// } -// return (PGDataSourceConfig) importConfig; -// } - - @Override - public DataSourceConfig clone() { - try { - DataSourceConfig clone = (DataSourceConfig) super.clone(); - // le clonage est effectue sur les references et donc - // on se retrouve sur le meme object dbConfig et cela - // n'est pas souhaitable (isolation des configurations) - ((AbstractDataSourceConfig) clone).dbConfig = cloneConfig(null); - // Attention le clone recopie la reference sur la liste des policy - // ce qui n'est pas bon car les deux listes doivent etre - // independances, on effectue donc une recopie en profondeur - ((AbstractDataSourceConfig) clone).policy = EnumSet.noneOf(DataPolicy.class); - EnumSet<DataPolicy> policy1 = clone.getPolicy(); - if (!policy.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("will add policy : " + policy + " - " + System.identityHashCode(policy)); - } - policy1.addAll(policy); - } - return clone; - } catch (CloneNotSupportedException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public void copyTo(DataSourceConfig config) { - config.setShortLabel(shortLabel); - config.setUseCache(useCache); - config.setCanMigrate(isCanMigrate()); - config.setShowMigrationSql(isShowMigrationSql()); - cloneConfig(config.getDbConfig()); - - config.getPolicy().clear(); - if (!policy.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("add policy : " + policy); - } - config.getPolicy().addAll(policy); - } - } - - @SuppressWarnings("unchecked") - @Override - public <T> T get(DataSourceConfigParam param, Class<T> type) { - return (T) dbConfig.get(param.getMapName()); - } - - @Override - public void set(DataSourceConfigParam param, Object value) { - if (value == null) { - if (log.isDebugEnabled()) { - log.debug("remove param " + param); - } - dbConfig.remove(param.getMapName()); - } else { - if (log.isDebugEnabled()) { - log.debug("update param " + param + " with value " + value); - } - dbConfig.put(param.getMapName(), value); - } - } - - @Override - public String getPolicyLabel() { - StringBuilder buffer = new StringBuilder(); - buffer.append("\n\n"); - buffer.append(t("observe.storage.remote.wrights")); - buffer.append(" : "); - boolean read, write; - read = getPolicy().contains(DataPolicy.READ_REFERENTIEL); - write = getPolicy().contains(DataPolicy.WRITE_REFERENTIEL); - buffer.append("\n - "); - fillWrights(buffer, read, write, - t("observe.storage.dataPolicy.referentiel")); - - read = getPolicy().contains(DataPolicy.READ_DATA); - write = getPolicy().contains(DataPolicy.WRITE_DATA); - buffer.append("\n - "); - fillWrights(buffer, read, write, - t("observe.storage.dataPolicy.data")); - -// for (DataPolicy p : getPolicy()) { -// buffer.append("\n - ").append(t(p.getLabel())); -// } - return buffer.toString(); - } - - public void fillWrights(StringBuilder buffer, boolean read, - boolean write, String label) { - - buffer.append(t(label)).append(" : "); - if (!read && !write) { - buffer.append(t("observe.storage.dataPolicy.no.wrights")); - return; - } - - if (read && write) { - buffer.append(t("observe.storage.dataPolicy.readWrite")); - return; - } - if (read) { - buffer.append(t("observe.storage.dataPolicy.read")); - } - if (write) { - buffer.append(t("observe.storage.dataPolicy.write")); - } - - } - - protected void checkParam(DataSourceConfigParam... requiredParams) { - for (DataSourceConfigParam p : requiredParams) { - if (get(p, p.getType()) == null) { - throw new IllegalStateException( - "could not find parameter [" + p.getPropertyName() + - "] in configuration!"); - } - } - } - - protected Properties cloneConfig(Properties dbConfig1) { - if (dbConfig1 == null) { - dbConfig1 = new Properties(); - } else { - dbConfig1.clear(); - } - for (Object k : dbConfig.keySet()) { - Object value = dbConfig.get(k); - // on clone la configuration - if (value instanceof DataSourceConfig) { - value = ((DataSourceConfig) value).clone(); - } - dbConfig1.put(k, value); - } - return dbConfig1; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSourceProvider.java b/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSourceProvider.java deleted file mode 100644 index 5c739e6..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/AbstractDataSourceProvider.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import com.google.common.base.Preconditions; -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceConfigParam; -import fr.ird.observe.db.DataSourceProvider; -import fr.ird.observe.db.constants.CommonDataSourceConfigParam; -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.hibernate.cfg.Environment; -import org.hibernate.dialect.Dialect; -import org.nuiton.topia.framework.TopiaConnectionProvider; -import org.nuiton.topia.migration.TopiaMigrationEngine; -import org.nuiton.topia.migration.TopiaMigrationService; -import org.nuiton.topia.replication.TopiaReplicationService; -import org.nuiton.topia.replication.TopiaReplicationServiceImpl; - -import java.lang.reflect.Constructor; -import java.sql.Driver; -import java.sql.DriverManager; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import static org.nuiton.i18n.I18n.t; - -/** - * L'implantation abstraite de base pour un fournisseur de configuration et - * service. - * - * @param <C> le type de configuration - * <p/> - * Note: l'ordre naturel de cet objet est basé sur {@link #configClass} et - * {@link #serviceClass}. - * @author Tony Chemit - chemit@codelutin.com - * @see DataSourceProvider - * @see DataSourceConfig - * @see DataSource - * @since 1.0 - */ -public abstract class AbstractDataSourceProvider<C extends DataSourceConfig, S extends DataSource> implements DataSourceProvider<C, S> { - - protected final Class<C> configClass; - - protected final Class<S> serviceClass; - - protected final Constructor<C> configClassConstructor; - - protected final Constructor<S> serviceClassConstructor; - - protected final Class<? extends Dialect> dialectClass; - - protected final Class<? extends Driver> driverClass; - - protected final Class<? extends AbstractDataSourceMigration> migrationClass; - - protected final DataSourceConfigParam[] params; - - protected AbstractDataSourceProvider( - Class<C> configClass, - Class<S> serviceClass, - Class<? extends Dialect> dialectClass, - Class<? extends Driver> driverClass, - Class<? extends AbstractDataSourceMigration> migrationClass, - DataSourceConfigParam... params) throws NullPointerException, - IllegalArgumentException { - - Preconditions.checkNotNull(dialectClass, "dialect can not be null"); - Preconditions.checkNotNull(driverClass, "driver can not be null"); - Preconditions.checkNotNull(configClass, "configClass can not be null"); - Preconditions.checkNotNull(serviceClass, "serviceClass can not be null"); - Preconditions.checkNotNull(migrationClass, "migrationClass can not be null"); - - try { - serviceClassConstructor = serviceClass.getConstructor(configClass); - } catch (Exception ex) { - throw new IllegalArgumentException( - "could not find constructor " + serviceClass + - "(" + configClass + ")", ex); - } - try { - configClassConstructor = configClass.getConstructor( - String.class, Properties.class); - } catch (Exception ex) { - throw new IllegalArgumentException( - "could not find constructor " + configClass + "(" + - String.class + "," + Properties.class + ")", ex); - } - this.configClass = configClass; - this.serviceClass = serviceClass; - this.dialectClass = dialectClass; - this.driverClass = driverClass; - this.migrationClass = migrationClass; - this.params = params; - - // on enregiste le driverClass, sinon il n'est pas retrouve dans les - // tests de maven, voir pourquoi... - try { - DriverManager.registerDriver(getDriverClass().newInstance()); - } catch (Exception ex) { - throw new IllegalArgumentException( - "could not register driver " + driverClass + - " in DriverManager for reason : " + ex.getMessage(), ex); - } - } - - @Override - public Class<C> getConfigClass() { - return configClass; - } - - @Override - public Class<S> getServiceClass() { - return serviceClass; - } - - @Override - public Class<? extends Dialect> getDialectClass() { - return dialectClass; - } - - @Override - public Class<? extends Driver> getDriverClass() { - return driverClass; - } - - @Override - public Class<? extends AbstractDataSourceMigration> getMigrationClass() { - return migrationClass; - } - - @Override - public DataSourceConfigParam[] getParams() { - return params; - } - - @Override - public C newConfig(String label, Object... params) { - - if (label == null) { - throw new NullPointerException("label can not be null"); - } - - if (params.length % 2 == 1) { - throw new IllegalArgumentException( - "params must be some couples of (ConfigParam,Object), " + - "but had here " + params.length + " parameters"); - } - - for (int i = 0, j = params.length; i < j; i += 2) { - Object key = params[i]; - if (key == null || !(key instanceof DataSourceConfigParam)) { - throw new IllegalArgumentException( - "params must be some couples of (ConfigParam,Object)," + - " but parameter " + i + " was not a String : " + key); - } - } - - Map<DataSourceConfigParam, Object> detectedParams = - detectParameters(params); - - Properties dbConf = prepareTopiaConfig(); - - C result; - try { - - result = configClassConstructor.newInstance(label, dbConf); - - } catch (Exception ex) { - String cause = ex.getMessage(); - if (ex.getCause() != null) { - cause = ex.getCause().getLocalizedMessage(); - } - throw new RuntimeException( - t("observe.storage.error.newConfig", configClass, cause), - ex); - } - - applyParameters(result, detectedParams); - - return result; - } - - @Override - public S newService(C config) { - try { - S service = serviceClassConstructor.newInstance(config); - return service; - } catch (Exception ex) { - String cause = ex.getMessage(); - if (ex.getCause() != null) { - cause = ex.getCause().getLocalizedMessage(); - } - throw new RuntimeException( - t("observe.storage.error.newService", serviceClass, cause), - ex); - } - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - DataSourceProvider<?, ?> other = (DataSourceProvider<?, ?>) obj; - return configClass == other.getConfigClass() && - serviceClass == other.getServiceClass(); - } - - @Override - public int hashCode() { - int hash = 3; - hash = 97 * hash + configClass.hashCode(); - hash = 97 * hash + serviceClass.hashCode(); - return hash; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - protected Map<DataSourceConfigParam, Object> detectParameters( - Object... params) throws IllegalArgumentException { - - Map<DataSourceConfigParam, Object> result = - new HashMap<DataSourceConfigParam, Object>(); - - List<DataSourceConfigParam> universe = Arrays.asList(getParams()); - - for (int i = 0, j = params.length; i < j; i += 2) { - DataSourceConfigParam p = (DataSourceConfigParam) params[i]; - Object value = params[i + 1]; - if (universe.contains(p)) { - if (value != null) { - result.put(p, value); - } - continue; - } - - // paramètre non connu - throw new IllegalArgumentException( - "the parameter name " + p + " is unkown for provider " + - this); - } - - if (!result.containsKey(CommonDataSourceConfigParam.CREATION_MODE)) { - - // si aucun mode de création fournit, on ne fait pas d'opération - // de création à l'ouverture du service - result.put(CommonDataSourceConfigParam.CREATION_MODE, null); - } - return result; - } - - protected void applyParameters(C config, - Map<DataSourceConfigParam, Object> params) { - for (DataSourceConfigParam p : params.keySet()) { - config.set(p, params.get(p)); - } - } - - /** - * Prepare la configuration a donner a ToPIA. - * - * @return la configuration pour ToPIA. - */ - protected Properties prepareTopiaConfig() { - Properties config = new Properties(); - DBHelper.addHibernateMapping(config); - // On utilise pas cglib pour eviter les OutOfMemory: PermGen - System.setProperty(Environment.BYTECODE_PROVIDER, "javassist"); - config.setProperty(Environment.DIALECT, getDialectClass().getName()); - config.setProperty(Environment.DRIVER, getDriverClass().getName()); - - // utilisation du driver de connexion de topia - config.setProperty(Environment.CONNECTION_PROVIDER, TopiaConnectionProvider.class.getName()); - - if (ObserveServiceHelper.isInit()) { - IObserveConfig observeConfig = ObserveServiceHelper.get().getConfig(); - if (observeConfig != null) { - boolean showSql = observeConfig.isShowSql(); - config.setProperty(Environment.SHOW_SQL, String.valueOf(showSql)); - } - } - - // correct error : org.hibernate.HibernateException: No CurrentSessionContext configured! - config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); -// config.setProperty(Environment.CACHE_PROVIDER, "org.hibernate.cache.EhCacheProvider"); -// config.setProperty(Environment.CACHE_PROVIDER_CONFIG, "observe-ehcache.xml"); -// config.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); -// config.setProperty(Environment.USE_REFLECTION_OPTIMIZER, "true"); - - // ajout service de replication - config.setProperty(TopiaReplicationService.TOPIA_SERVICE_NAME, - TopiaReplicationServiceImpl.class.getName()); - - // ajout service de migration - - config.setProperty( - TopiaMigrationService.TOPIA_SERVICE_NAME, - TopiaMigrationEngine.class.getName()); - config.setProperty( - TopiaMigrationEngine.MIGRATION_CALLBACK, - getMigrationClass().getName()); - - // Note : - // on ne veut jamais lancer la migration a l'init - // car on controle la creation du schema et cela peut poser probleme - config.setProperty( - TopiaMigrationEngine.MIGRATION_MIGRATE_ON_INIT, - String.valueOf(false)); - return config; - } - - /** - * Ajoute aux parametres specifiques donnes, les parametres commun. - * - * @param values les parametres specifiques au service - * @return tous les parametres connus pour le service - */ - protected static DataSourceConfigParam[] values(DataSourceConfigParam... values) { - List<DataSourceConfigParam> params = new ArrayList<DataSourceConfigParam>(); - params.addAll(Arrays.asList(CommonDataSourceConfigParam.values())); - params.addAll(Arrays.asList(values)); - return params.toArray(new DataSourceConfigParam[params.size()]); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSource.java b/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSource.java deleted file mode 100644 index 806fde4..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSource.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.db.constants.DataSourceState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.persistence.util.TopiaEntityHelper; - -import java.io.File; -import java.net.URL; - -import static org.nuiton.i18n.I18n.t; -import static org.nuiton.topia.persistence.util.TopiaEntityHelper.saveDB; - -/** - * L'implantation de {@link DataSource} pour les base h2. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class H2DataSource extends AbstractDataSource { - - /** Logger */ - private static final Log log = LogFactory.getLog(H2DataSource.class); - - public H2DataSource(H2DataSourceConfig config) { - super(config); - } - - @Override - public H2DataSourceConfig getConfig() { - return (H2DataSourceConfig) super.getConfig(); - } - - @Override - protected void open() throws DataSourceException { - super.open(); - - // go back in init state, in case there some problems in the following code - // we will stay coherent and block any others objectOperations on the service - state = DataSourceState.INIT; - - boolean mustCreateSchema = false; - - H2DataSourceConfig config = getConfig(); -// DataSourceConfig importConfig = null; - - try { - if (config.getCreationMode() != null) { - switch (config.getCreationMode()) { - case IMPORT_INTERNAL_DUMP: - case IMPORT_EXTERNAL_DUMP: - URL dbDump = config.getDbDump(); - fireNewMessage( - t("observe.storage.message.create.from.script", getLabel(), dbDump.toString())); - - // create database from selected dump - TopiaEntityHelper.createDBFromSQL( - config.getDataDirectory(), rootCtxt, dbDump.toURI()); - break; - case EMPTY: - mustCreateSchema = true; - - break; - case IMPORT_LOCAL_STORAGE: - mustCreateSchema = true; -// importConfig = config.getImportConfig(); - break; - - case IMPORT_REMOTE_STORAGE: - mustCreateSchema = true; -// importConfig = config.getImportConfig(); - break; - } - } - - createSchemaOrUpdate(mustCreateSchema, config.isCanMigrate()); - - if (config.hasImportReferentielConfig()) { - - DataSourceConfig importConfig = config.getImportConfig(); - importReferentiel(importConfig); - } - -// if (importConfig != null) { -// importReferentiel(importConfig); -// } - - } catch (Exception ex) { - if (ex instanceof DataSourceException) { - throw (DataSourceException) ex; - } - String txName = "open"; - throw new DataSourceException(ex, txName); - } - - // can safely now pass to open state - state = DataSourceState.OPEN; - } - - @Override - protected void createSchema(String schemaName) { - TopiaContext tx = rootCtxt.beginTransaction(); - try { - tx.executeSQL("CREATE SCHEMA IF NOT EXISTS " + schemaName + ";"); - tx.commitTransaction(); - } finally { - tx.closeContext(); - } - } - - @Override - public void storeDB(File gzipFile) throws DataSourceException { - String txName = "storeDB"; - TopiaContext tx = beginTransaction(txName); - try { - if (log.isInfoEnabled()) { - log.info("save local db to " + gzipFile); - } - - fireNewMessage(t("observe.storage.message.storeDB", gzipFile.getAbsolutePath())); - - saveDB(gzipFile, tx); - } catch (Exception ex) { - throw new DataSourceException(ex, txName); - } finally { - closeTransaction(tx, txName); - } - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceConfig.java b/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceConfig.java deleted file mode 100644 index 5a0371b..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceConfig.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import com.google.common.collect.Sets; -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.constants.CommonDataSourceConfigParam; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DataPolicy; -import org.hibernate.cfg.Environment; - -import java.io.File; -import java.net.URL; -import java.util.Properties; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * La configuration d'un service de persistance sur une base de type H2. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class H2DataSourceConfig extends AbstractDataSourceConfig { - - /** l'url d'acces a la base locale */ - public static final String h2LocalUrl = - "jdbc:h2:file:%s;" + - // on peut aussi utiliser file, socket - "FILE_LOCK=file;" + - //1 or 2 is needed to restore avec crash - // 0: logging is disabled (faster), - // 1: logging of the data is enabled, but logging of the index - // changes is disabled (default), 2: logging of both data and index - // changes are enabled - "LOG=0;" + - // on peut aussi utiliser hsqldb, mysql ou postgresql - "MODE=postgresql;" + - //"MODE=hsqldb;" + - // Sets the default lock timeout (in milliseconds) in this - // database that is used for the new sessions. - "DEFAULT_LOCK_TIMEOUT=2000;" + - // -1: the database is never closed until the close delay is set to - // some other rev or SHUTDOWN is called., 0: no delay (default; the - // database is closed if the last connection to it is closed)., n: - // the database is left open for n second after the last connection - // is closed. - "DB_CLOSE_DELAY=0;" + - // 0: no locking (should only be used for testing), - // 1: table level locking (default), - // 2: table level locking with garbage collection (if the - // application does not close all connections). - // LOCK_MODE 3 (READ_COMMITTED). Table level locking, but only when - // writing (no read locks). - "LOCK_MODE=3;" + - // Levels: 0=off, 1=error, 2=info, 3=debug. - "TRACE_LEVEL_FILE=0;" + - // on system.out: 0=off, 1=error, 2=info, 3=debug. - "TRACE_LEVEL_SYSTEM_OUT=0;" + - // maximumn cache to improve performance... - "CACHE_SIZE=65536"; - - public H2DataSourceConfig(String label) { - super(label); - } - - public H2DataSourceConfig(String label, Properties dbConfig) { - super(label, dbConfig); - } - - @Override - public void init() { - - // check required parameters - checkParam( - H2DataSourceConfigParam.DIRECTORY, - H2DataSourceConfigParam.NAME, - CommonDataSourceConfigParam.LOGIN, - CommonDataSourceConfigParam.PASSWORD - ); - - File dataDirectory = getDataDirectory(); - String dbName = new File(dataDirectory, getName()).getPath(); - String url = String.format(h2LocalUrl, dbName); - dbConfig.setProperty(Environment.URL, url); - } - - @Override - public String getLabel() { - String result = getShortLabel(); - File d = getDataDirectory(); - return result + ' ' + (d == null ? "undefined" : d.getAbsolutePath()); - } - - @Override - public boolean isValid() { - if (getCreationMode() == null) { - - // utilisation direct d'une base existante - return isStorageExists() && - getStorageDirectory().isDirectory(); - } - - boolean validate = getCreationMode() != null; - - if (validate) { - switch (getCreationMode()) { - case EMPTY: - // rien a tester - break; - case IMPORT_INTERNAL_DUMP: - // rien a tester - break; - case IMPORT_EXTERNAL_DUMP: - validate = getDbDump() != null; - if (validate) { - // attention, les espaces sont encodee dans une url, - // il faut donc les decoder si on veut recuperer le - // chemit du fichier - //FIXME on devrait ne plus utiliser d'url pour eviter - //FIXME ce probleme. - String path = - getDbDump().getFile().replaceAll("%20", " "); - File dumpFile = new File(path); - validate = dumpFile != null && - dumpFile.exists() && - dumpFile.getName().endsWith(".sql.gz"); - } - break; - case IMPORT_LOCAL_STORAGE: { - DataSourceConfig c = getImportConfig(); - validate = c != null && c.isValid(); - } - break; - case IMPORT_REMOTE_STORAGE: { - DataSourceConfig c = getImportConfig(); - validate = c != null && c.isValid(); - } - } - } - return validate; - } - -// public CreationMode getCreationMode() { -// return get(CommonDataSourceConfigParam.CREATION_MODE, CreationMode.class); -// } -// -// public void setCreationMode(CreationMode creationMode) { -// set(CommonDataSourceConfigParam.CREATION_MODE, creationMode); -// } - - public URL getDbDump() { - return get(H2DataSourceConfigParam.DUMP, URL.class); - } - - public void setDbDump(URL dbDump) { - set(H2DataSourceConfigParam.DUMP, dbDump); - } - - public boolean isStorageExists() { - return getStorageDirectory() != null && getStorageDirectory().exists(); - } - - public String getName() { - return get(H2DataSourceConfigParam.NAME, String.class); - } - - public void setName(String name) { - set(H2DataSourceConfigParam.NAME, name); - } - - public File getStorageDirectory() { - return get(H2DataSourceConfigParam.DIRECTORY, File.class); - } - - public void setStorageDirectory(File storageDirectory) { - set(H2DataSourceConfigParam.DIRECTORY, storageDirectory); - } - - public File getDataDirectory() { - if (getStorageDirectory() == null || getName() == null) { - return null; - } - return new File(getStorageDirectory(), getName()); - } - - @Override - public void detectPolicy() { - policy.clear(); - // Sur une base locale on peut modifier les données - // utilisateurs mais jamais le référentiel - policy.add(DataPolicy.READ_REFERENTIEL); - policy.add(DataPolicy.READ_DATA); - policy.add(DataPolicy.WRITE_DATA); - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(128); - buffer.append("\n - "); - buffer.append(t("observe.storage.h2.login")); - buffer.append(" : "); - buffer.append(getLogin()); - buffer.append(getPolicyLabel()); - return buffer.toString(); - } - - @Override - public H2DataSourceConfig clone() { - return (H2DataSourceConfig) super.clone(); - } - - Set<CreationMode> IMPORT_REFERENTIEL_MODES = Sets.newHashSet(CreationMode.IMPORT_LOCAL_STORAGE, - CreationMode.IMPORT_REMOTE_STORAGE); - - @Override - public boolean hasImportReferentielConfig() { - boolean hasImport = super.hasImportReferentielConfig(); - if (hasImport) { - - CreationMode creationMode = getCreationMode(); - hasImport = creationMode != null && IMPORT_REFERENTIEL_MODES.contains(creationMode); - - } - return hasImport; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceConfigParam.java b/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceConfigParam.java deleted file mode 100644 index 1826d4e..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceConfigParam.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.db.DataSourceConfigParam; -import fr.ird.observe.db.constants.CreationMode; - -import java.io.File; -import java.net.URL; - -/** - * Les différents paramètres disponibles pour la configuration d'un service de - * persistance sur une base H2. - * <p/> - * Une base H2 se trouve dans un répertoire de la forme : - * <p/> - * (storageDirectory)/(name) - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum H2DataSourceConfigParam implements DataSourceConfigParam { - - /** - * le lastName de la base H2. - * <p/> - * Ce lastName est le lastName du répertoire ou sont les données. - * <p/> - * Par défault, si non renseigné on utilisera le lastName "obstuna". - */ - NAME("name", String.class), - - /** - * L'url d'une sauvegarde à charger dans la base H2 lors de sa création. - * <p/> - * Cette donnée sera utilisée uniquement si le mode de création est : - * <p/> - * {@link CreationMode#IMPORT_EXTERNAL_DUMP} ou {@link - * CreationMode#IMPORT_INTERNAL_DUMP}. - */ - DUMP("dump", URL.class), - - /** - * le répertoire principal du service de persistance. Il s'agit du - * répertoire parent du répertoire des données. - */ - DIRECTORY("directory", File.class); - - private final String mapName; - - private final String propertyName; - - private final Class<?> type; - - H2DataSourceConfigParam(String name, Class<?> type) { - this(name, name, type); - } - - H2DataSourceConfigParam(String propertyName, - String mapName, - Class<?> type) { - this.mapName = mapName; - this.propertyName = propertyName; - this.type = type; - } - - @Override - public String getMapName() { - return mapName; - } - - @Override - public String getPropertyName() { - return propertyName; - } - - @Override - public Class<?> getType() { - return type; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceProvider.java b/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceProvider.java deleted file mode 100644 index 1426010..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/H2DataSourceProvider.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.db.DataSourceConfigParam; -import fr.ird.observe.entities.migration.H2DataSourceMigration; -import org.h2.Driver; -import org.hibernate.dialect.H2Dialect; - -import java.util.Map; - -/** - * Le fournisseur de configuration et service sur base H2. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class H2DataSourceProvider extends AbstractDataSourceProvider<H2DataSourceConfig, H2DataSource> { - - public H2DataSourceProvider() { - super( - H2DataSourceConfig.class, - H2DataSource.class, - H2Dialect.class, - Driver.class, - H2DataSourceMigration.class, - values(H2DataSourceConfigParam.values())); - } - - @Override - protected Map<DataSourceConfigParam, Object> detectParameters( - Object... params) { - Map<DataSourceConfigParam, Object> detectedParams = - super.detectParameters(params); - if (!detectedParams.containsKey(H2DataSourceConfigParam.NAME)) { - // on utilise par defaut "obsutna" si aucun lastName n'est fournit - detectedParams.put(H2DataSourceConfigParam.NAME, "obstuna"); - } -// if (!detectedParams.containsKey(CommonDataSourceConfigParam.CREATION_MODE)) { -// // si aucun mode de création fournit, on ne fait pas d'opération -// // de création à l'ouverture du service -// detectedParams.put(CommonDataSourceConfigParam.CREATION_MODE, null); -// } - return detectedParams; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSource.java b/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSource.java deleted file mode 100644 index efe81cd..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSource.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.db.constants.DataSourceState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.io.File; -import java.util.Properties; -import java.util.Set; - -/** - * L'implantation de {@link DataSource} pour - * les bases postgres. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class PGDataSource extends AbstractDataSource { - - /** Logger */ - private static final Log log = LogFactory.getLog(PGDataSource.class); - - public PGDataSource(PGDataSourceConfig config) { - super(config); - } - - @Override - public PGDataSourceConfig getConfig() { - return (PGDataSourceConfig) super.getConfig(); - } - - @Override - public Properties getConfigForTopia() { - Properties topia = super.getConfigForTopia(); - if (getConfig().isUseSsl()) { - // ajout de ?ssl=true a la fin de l'url - - String newUrl = getConfig().getFullUrl(); - topia.put(PGDataSourceConfigParam.URL.getMapName(), newUrl); - if (log.isInfoEnabled()) { - log.info("Will use ssl url : " + newUrl); - } - } - return topia; - } - - @Override - protected void open() throws DataSourceException { - - PGDataSourceConfig config = getConfig(); - super.open(); - - // go back in init state, in case there some problems in the - // following code we will stay coherent and block any others - // objectOperations on the service - state = DataSourceState.INIT; - try { - - boolean mustCreateSchema = false; -// DataSourceConfig importConfig = null; - if (config.getCreationMode() != null) { - switch (config.getCreationMode()) { - case IMPORT_INTERNAL_DUMP: - case IMPORT_LOCAL_STORAGE: - - // cas impossible pour une base de type pg - throw new IllegalStateException("Can not use the creationMode " + config.getCreationMode() + " for a postgres data source"); - - case IMPORT_EXTERNAL_DUMP: - mustCreateSchema = true; -// importConfig = config.getH2ImportConfig(); - break; - case EMPTY: - mustCreateSchema = true; - break; - - case IMPORT_REMOTE_STORAGE: - mustCreateSchema = true; -// importConfig = config.getPGImportConfig(); - break; - } - } - - createSchemaOrUpdate(mustCreateSchema, config.isCanMigrate()); - -// if (importConfig != null) { -// -// importReferentiel(importConfig); -// } - - if (config.hasImportReferentielConfig()) { - - DataSourceConfig importConfig = config.getImportConfig(); - importReferentiel(importConfig); - } - - if (config.hasImportDataConfig()) { - - DataSourceConfig importDataConfig = config.getImportDataConfig(); - - Set<String> importDataIds = config.getImportDataIds(); - - importData(importDataConfig, importDataIds); - } - - } catch (Exception eee) { - if (eee instanceof DataSourceException) { - throw (DataSourceException) eee; - } - String txName = "open"; - throw new DataSourceException(eee, txName); - } - - // on peut au final passer en mode ouvert si aucune erreur - // n'est survenue - state = DataSourceState.OPEN; - } - - @Override - protected void beforeClose(boolean destroy) throws DataSourceException { - super.beforeClose(destroy); - if (destroy) { - throw new IllegalArgumentException( - "can not destroy a postgres db!"); - } - } - - @Override - public void storeDB(File gzipFile) throws DataSourceException { - throw new IllegalStateException( - "remote storage can not be stored in a gzipfile..."); - } - - @Override - protected void createSchema(String schemaName) { - TopiaContext tx = rootCtxt.beginTransaction(); - try { - tx.executeSQL("CREATE SCHEMA " + schemaName + ";"); - tx.commitTransaction(); - } catch (TopiaException e) { - - if (log.isErrorEnabled()) { - log.error("Could not create schema...", e); - } - } finally { - tx.closeContext(); - } - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceConfig.java b/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceConfig.java deleted file mode 100644 index 150ca7a..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceConfig.java +++ /dev/null @@ -1,470 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import com.google.common.collect.Sets; -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceConfigParam; -import fr.ird.observe.db.constants.CommonDataSourceConfigParam; -import fr.ird.observe.db.constants.ConnexionStatus; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DataPolicy; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.version.Version; -import org.nuiton.version.Versions; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class PGDataSourceConfig extends AbstractDataSourceConfig { - - /** Logger */ - private static final Log log = LogFactory.getLog(PGDataSourceConfig.class); - - public static final String DATA_PRIVILEGES = "dataPrivileges"; - - public static final String REFERENTIEL_PRIVILEGES = "referentielPrivileges"; - - protected ConnexionStatus connexionStatus; - - protected SQLException connexionError; - - protected Version version; - - public PGDataSourceConfig(String label) { - super(label); - } - - public PGDataSourceConfig(String label, Properties dbConfig) { - super(label, dbConfig); - } - - @Override - public String getLabel() { - String result = getShortLabel(); - return result + " : " + getUrl(); - } - - public String getUrl() { - return get(PGDataSourceConfigParam.URL, String.class); - } - - public String getFullUrl() { - String s = getUrl(); - if (isUseSsl()) { - // see http://jdbc.postgresql.org/documentation/91/ssl-client.html - s += "?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; - } - return s; - } - - public void setUrl(String url) { - set(PGDataSourceConfigParam.URL, url); - } - - public boolean isUseSsl() { - Boolean b = get(PGDataSourceConfigParam.USE_SSL, Boolean.class); - return b != null && b; - } - - public void setUseSsl(boolean useSsl) { - set(PGDataSourceConfigParam.USE_SSL, useSsl); - } - - public ConnexionStatus getConnexionStatus() { - return connexionStatus == null ? ConnexionStatus.UNTESTED : - connexionStatus; - } - - public void setConnexionStatus(ConnexionStatus connexionStatus) { - this.connexionStatus = connexionStatus; - } - - public SQLException getConnexionError() { - return connexionError; - } - - public Version getVersion() { - return version; - } - - @Override - public void init() { - - // check required parameters - - checkParam(PGDataSourceConfigParam.URL, - CommonDataSourceConfigParam.LOGIN, - CommonDataSourceConfigParam.PASSWORD); - } - - @Override - public boolean isValid() { - boolean validate = true; - if (getCreationMode() != null) { - - // un mode de creation est positionne, on le valide - switch (getCreationMode()) { - case EMPTY: - case IMPORT_INTERNAL_DUMP: - case IMPORT_EXTERNAL_DUMP: - case IMPORT_LOCAL_STORAGE: - - // modes interdits pour le moment - validate = false; - break; - case IMPORT_REMOTE_STORAGE: - // si une configuration d'import de referentiel, on la valide - validate = getImportConfig() == null || getImportConfig().isValid(); - break; - } - } - - // au final, c'est valide uniquement si cela a été testé. - validate &= connexionStatus != null && - connexionStatus == ConnexionStatus.SUCCESS; - return validate; - } - - Set<CreationMode> IMPORT_REFERENTIEL_MODES = Sets.newHashSet(CreationMode.IMPORT_EXTERNAL_DUMP, - CreationMode.IMPORT_REMOTE_STORAGE); - - @Override - public boolean hasImportReferentielConfig() { - boolean hasImport = super.hasImportReferentielConfig(); - if (hasImport) { - - CreationMode creationMode = getCreationMode(); - hasImport = creationMode != null && IMPORT_REFERENTIEL_MODES.contains(creationMode); - - } - return hasImport; - } - - @Override - public void copyTo(DataSourceConfig config) { - super.copyTo(config); - - PGDataSourceConfig c = (PGDataSourceConfig) config; - c.connexionStatus = connexionStatus; - c.connexionError = connexionError; - c.version = version; - } - - @Override - public void set(DataSourceConfigParam param, Object value) { - super.set(param, value); - // a chaque modification de la configuration - // on force le test de connexion - connexionStatus = ConnexionStatus.UNTESTED; - } - - /** - * Pour tester la connexion distante. - * <p/> - * L'appel a cette méthode change l'état du champ {@link #connexionStatus}. - * <p/> - * Si une erreur a été rencontrée, elle est sauvé dans le champs {@link - * #connexionError} pour être affiché par l'ui par exemple et {@link - * #connexionStatus} passe alors en état {@link ConnexionStatus#FAILED}. - * - * @return {@code true} si la connexion a pu être établie. - */ - public boolean canConnect() { - - // a chaque nouvelle tentative de connexion, on suppose qu'il n'y a - // pas d'erreur - connexionError = null; - - String url = getFullUrl(); - String login = getLogin(); - char[] password = getPassword(); - - dbConfig.remove(DATA_PRIVILEGES); - dbConfig.remove(REFERENTIEL_PRIVILEGES); - - ResultSet observerDataPrivilege; - - Set<String> dataPrivileges = new HashSet<String>(); - Set<String> referentielPrivileges = new HashSet<String>(); - String p = password == null ? null : new String(password); - Connection conn = null; - try { - conn = DriverManager.getConnection(url, login, p); - - if (log.isDebugEnabled()) { - log.debug("connexion reussie pour l'utilisateur " + login + - " at [" + url + ']'); - } - // la connexion est reussie, on recherche les droits de - // l'utilisateur sur cette base - - //TODO chemit 2010-10-28 : il vaudrait mieux utiliser les fonctions postgres adpéquates qui elle sont fiables... - //FIXME la recuperation des meta-donnees n'est pas fiable! - //FIXME en effet, sur un simple lecteur, on voit apparaître aussi - //FIXME des privileges INSERT ou UPDATE... - - // on pourrait utiliser une requete specifique postgres : - - // select count(*) from information_schema.table_privileges where - // grantee='ROLE' and table_name='maree' and - // privilege_type='INSERT'; - - // cependant cela n'est pas mieux car la requete peut ne pas etre - // extacte si l'utilisateur n'a pas les bons droits.... - - // la meilleure solution serait je pense de poser 2 fonctions - // stockées dans pg canWriteData, canWrite pour etre sur du resultat - - // recherche des droits sur les données observers - - observerDataPrivilege = conn.getMetaData().getTablePrivileges( - null, null, "trip"); - - ResultSetMetaData metaData = observerDataPrivilege.getMetaData(); - int columnCount = metaData.getColumnCount(); - if (log.isDebugEnabled()) { - log.debug("meatadata count : " + columnCount); - } - for (int i = 1; i <= columnCount; i++) { - if (log.isDebugEnabled()) { - log.debug("metadata " + i + " : " + metaData.getColumnName(i)); - } - } - while (observerDataPrivilege.next()) { - String security = - observerDataPrivilege.getString("PRIVILEGE"); - String grantee = - observerDataPrivilege.getString("GRANTEE"); - if (grantee.equals(login)) { - if (log.isDebugEnabled()) { - log.debug("for maree table " + grantee + '/' + security); - } - dataPrivileges.add(security); - } - } - dbConfig.put(DATA_PRIVILEGES, dataPrivileges); - - // recherche des droits sur le referentiel - - observerDataPrivilege = conn.getMetaData().getTablePrivileges( - null, null, "vessel"); - while (observerDataPrivilege.next()) { - String security = - observerDataPrivilege.getString("PRIVILEGE"); - String grantee = - observerDataPrivilege.getString("GRANTEE"); - if (grantee.equals(login)) { - if (log.isDebugEnabled()) { - log.debug("for vessel table " + grantee + '/' + security); - } - referentielPrivileges.add(security); - } - } - dbConfig.put(REFERENTIEL_PRIVILEGES, referentielPrivileges); - - // on peut positionner les droits - detectPolicy(); - - } catch (SQLException e) { - connexionError = e; - connexionStatus = ConnexionStatus.FAILED; - return false; - } finally { - - try { - close(conn); - } catch (SQLException e) { - if (log.isErrorEnabled()) { - log.error(e); - } - } - } - - connexionError = null; - connexionStatus = ConnexionStatus.SUCCESS; - - // la connexion est valide - return true; - } - - public boolean checkVersion(Version dbVersion) { - - version = null; - - boolean result = false; - String url = getFullUrl(); - String login = getLogin(); - char[] password = getPassword(); - - String p = password == null ? null : new String(password); - Connection conn = null; - try { - conn = DriverManager.getConnection(url, login, p); - - if (log.isDebugEnabled()) { - log.debug("connexion reussie pour l'utilisateur " + login + - " at [" + url + ']'); - } - // la connexion est reussie, on recherche les droits de - // récupération de la version de la base - PreparedStatement preparedStatement = - conn.prepareStatement("SELECT version FROM tms_version;"); - ResultSet resultSet = preparedStatement.executeQuery(); - - if (resultSet.next()) { - String remoteVersionStr = resultSet.getString(1); - version = Versions.valueOf(remoteVersionStr); - result = dbVersion.equals(version); - } - - } catch (SQLException e) { - if (log.isErrorEnabled()) { - log.error("Could not get db version", e); - } - } finally { - - try { - close(conn); - } catch (SQLException e) { - if (log.isErrorEnabled()) { - log.error(e); - } - } - } - return result; - } - - /** - * Pour tester la connexion distante. - * <p/> - * L'appel a cette méthode change l'état du champ {@link #connexionStatus}. - * <p/> - * Si une erreur a été rencontrée, elle est sauvé dans le champs {@link - * #connexionError} pour être affiché par l'ui par exemple et {@link - * #connexionStatus} passe alors en état {@link ConnexionStatus#FAILED}. - * - * @return {@code true} si la connexion a pu être établie. - * @throws SQLException si la connexion n'est pas possible - */ - public Connection getSQLConnection() throws SQLException { - - // a chaque nouvelle tentative de connexion, on suppose qu'il n'y a - // pas d'erreur - connexionError = null; - - String url = getFullUrl(); - String login = getLogin(); - char[] password = getPassword(); - - dbConfig.remove(DATA_PRIVILEGES); - dbConfig.remove(REFERENTIEL_PRIVILEGES); - - String p = password == null ? null : new String(password); - Connection conn = DriverManager.getConnection(url, login, p); - - if (log.isDebugEnabled()) { - log.debug("connexion reussie pour l'utilisateur " + login + - " at [" + url + ']'); - } - conn.setAutoCommit(false); - return conn; - } - - @Override - public void detectPolicy() { - - policy.clear(); - // par défaut, tous les monde peut lire les données du référentiel - policy.add(DataPolicy.READ_REFERENTIEL); - Set<?> privileges = (Set<?>) - getDbConfig().get(DATA_PRIVILEGES); - if (CollectionUtils.isNotEmpty(privileges)) { - // seul les utilisateurs avec au moins un droit sur les donnes - // observer peut les lire - policy.add(DataPolicy.READ_DATA); - } - if (canWrite(privileges)) { - // l'utilisateur a le droit d'écrire des données observer - policy.add(DataPolicy.WRITE_DATA); - } - privileges = (Set<?>) - getDbConfig().get(REFERENTIEL_PRIVILEGES); - if (canWrite(privileges)) { - // l'utilisateur a le droit d'écrire sur le référentiel - policy.add(DataPolicy.WRITE_REFERENTIEL); - } - } - - @Override - public PGDataSourceConfig clone() { - return (PGDataSourceConfig) super.clone(); - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(300); - buffer.append("\n - "); - buffer.append(t("observe.storage.remote.url")); - buffer.append(" : "); - buffer.append(getUrl()); - buffer.append("\n - "); - buffer.append(t("observe.storage.remote.login")); - buffer.append(" : "); - buffer.append(getLogin()); - if (isUseSsl()) { - buffer.append("\n - "); - buffer.append(t("observe.storage.remote.isUsingSll")); - } - buffer.append(getPolicyLabel()); - return buffer.toString(); - } - - protected static boolean canWrite(Set<?> privileges) { - boolean result = privileges != null && - privileges.contains("DELETE") && - privileges.contains("UPDATE") && - privileges.contains("INSERT"); - return result; - } - - public void close(Connection conn) throws SQLException { - if (conn != null) { - conn.close(); - } - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceConfigParam.java b/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceConfigParam.java deleted file mode 100644 index e6e74b7..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceConfigParam.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.db.DataSourceConfigParam; -import org.hibernate.cfg.Environment; - -/** - * Les différents paramètres disponibles pour la configuration d'un service de - * persistance sur une base Postgres. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum PGDataSourceConfigParam implements DataSourceConfigParam { - - /** - * l'url d'acces au serveur postgres (doit etre de la forme - * jdbc://postgres...) - */ - URL("url", Environment.URL, String.class), - - /** un drapeau pour savoir si on utilise le mode ssl */ - USE_SSL("useSsl", Boolean.class); - -// /** le fichier du certifiat client si mode ssl activé */ -// SSL_CERTIFICAT_FILE("sslCertificatFile", File.class), -// -// /** le mot de passe du trust store si mode ssl activé */ -// SSL_CERTIFICAT_PASSWORD("sslCertificatPassword", char[].class); - - private final String mapName; - - private final String propertyName; - - private final Class<?> type; - - PGDataSourceConfigParam(String name, Class<?> type) { - this(name, name, type); - } - - PGDataSourceConfigParam(String propertyName, String mapName, Class<?> type) { - this.mapName = mapName; - this.propertyName = propertyName; - this.type = type; - } - - @Override - public String getMapName() { - return mapName; - } - - @Override - public String getPropertyName() { - return propertyName; - } - - @Override - public Class<?> getType() { - return type; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceProvider.java b/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceProvider.java deleted file mode 100644 index ee687ce..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/impl/PGDataSourceProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.entities.migration.PGDataSourceMigration; -import org.hibernate.dialect.PostgreSQL82Dialect; -import org.postgresql.Driver; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class PGDataSourceProvider - extends AbstractDataSourceProvider<PGDataSourceConfig, PGDataSource> { - - public PGDataSourceProvider() { - super( - PGDataSourceConfig.class, - PGDataSource.class, - PostgreSQL82Dialect.class, - Driver.class, - PGDataSourceMigration.class, - values(PGDataSourceConfigParam.values())); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/package-info.java b/observe-business/src/main/java/fr/ird/observe/db/package-info.java deleted file mode 100644 index 40e8cbc..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/package-info.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -/** - * Ce paquetage définit l'api des sources de données d'observe : - * {@link fr.ird.observe.db.DataSource}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -package fr.ird.observe.db; - diff --git a/observe-business/src/main/java/fr/ird/observe/db/util/PGInstall.java b/observe-business/src/main/java/fr/ird/observe/db/util/PGInstall.java deleted file mode 100644 index 23f6781..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/util/PGInstall.java +++ /dev/null @@ -1,555 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.util; - -import com.google.common.collect.Sets; -import fr.ird.observe.db.impl.PGDataSourceConfig; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.util.Scripts; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.migration.mappings.TMSVersionDAO; -import org.nuiton.topia.persistence.TopiaEntityEnum; -import org.nuiton.util.StringUtil; - -import java.net.URL; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -/** - * Usefull methods to install obstuna - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class PGInstall { - - /** Logger */ - private static final Log log = LogFactory.getLog(PGInstall.class); - - protected PGDataSourceConfig dataSourceConfig; - - protected SecurityModel securityModel; - - protected static final String DROP_TABLE_PATTERN = "DROP TABLE IF EXISTS %s.%s CASCADE;\n"; - - protected static final String DROP_SCHEMA_PATTERN = "DROP SCHEMA IF EXISTS %s CASCADE;\n"; - - protected static final String REVOKE_ON_TABLE_ALL_PATTERN = "REVOKE ALL ON %s.%s FROM %s CASCADE;\n"; - - protected static final String SET_ON_TABLE_OWNER_PATTERN = "ALTER TABLE %s.%s OWNER TO %s;\n"; - - protected static final String GRANT_ON_TABLE_READ_PATTERN = "GRANT SELECT ON %s.%s TO %s;\n"; - - protected static final String GRANT_ON_TABLE_ALL_PATTERN = "GRANT ALL ON %s.%s TO %s;\n"; - - protected static final String GRANT_ON_FUNCTION_PATTERN = "GRANT EXECUTE ON FUNCTION %s TO %s;\n"; - - protected static final String REVOKE_ON_SCHEMA_ALL_PATTERN = "REVOKE ALL ON SCHEMA %s FROM %s CASCADE;\n"; - - protected static final String REVOKE_ON_FUNCTIONS_PATTERN = "REVOKE EXECUTE ON FUNCTION %s FROM %s CASCADE;\n"; - - protected static final String GRANT_ON_SCHEMA_ALL_PATTERN = "GRANT USAGE ON SCHEMA %s TO %s;\n"; - - protected static final Set<String> EXTRA_TABLES = Sets.newHashSet(TMSVersionDAO.TABLE_NAME, - TMSVersionDAO.LEGACY_TABLE_NAME); - - protected static final Set<String> FUNCTION_NAMES_PREFIXS = Sets.newHashSet("ST_MakePoint", - "ST_SetSRID", - "sync_", - "tr_sync", - "ot_enhanced_school_type", - "observe_"); - - protected static final String SCHEMA_PUBLIC = "public"; - - protected static final Set<String> SCHEMAS = Sets.newHashSet(SCHEMA_PUBLIC, - "OBSERVE_COMMON", - "OBSERVE_SEINE", - "OBSERVE_LONGLINE"); - - protected static final Set<String> POSTGIS_TABLES = Sets.newHashSet("geometry_columns", "spatial_ref_sys"); - - public PGInstall() { - } - - public PGInstall(PGDataSourceConfig dataSourceConfig, SecurityModel securityModel) { - this.dataSourceConfig = dataSourceConfig; - this.securityModel = securityModel; - } - - public PGDataSourceConfig getDataSourceConfig() { - return dataSourceConfig; - } - - public SecurityModel getSecurityModel() { - return securityModel; - } - - public void init(PGDataSourceConfig dataSourceConfig, - SecurityModel securityModel, - boolean checkConnect) { - - this.dataSourceConfig = dataSourceConfig; - boolean b = !checkConnect || dataSourceConfig.canConnect(); - if (!b) { - throw new IllegalStateException( - "Could not connect to " + dataSourceConfig); - } - this.securityModel = securityModel; - } - - public void init(PGDataSourceConfig dataSourceConfig, - SecurityModel securityModel) { - init(dataSourceConfig, securityModel, true); - } - - /** - * Pour remplir une base de données à partir du script de la dernière - * version d'obstuna. - * - * @throws Exception pour toute erreur - */ - public abstract void execute() throws Exception; - - public void applySecurity() throws SQLException { - if (securityModel == null) { - throw new NullPointerException("securityModel can not be null"); - } - Connection conn = dataSourceConfig.getSQLConnection(); - try { - String script = createSecurityScript(conn); - loadScript(script); - } finally { - dataSourceConfig.close(conn); - } - } - - public void dropDb() throws SQLException { - Connection conn = dataSourceConfig.getSQLConnection(); - try { - String script = createDropScript(conn); - loadScript(script); - } finally { - dataSourceConfig.close(conn); - } - } - - /** - * Pour remplir une base de données à partir du {@code script} donné. - * - * @param script le script - * @throws Exception pour toute erreur - */ - public void createDb(URL script) throws Exception { - if (script == null) { - throw new NullPointerException("script parameter ca not be null!"); - } - - if (log.isInfoEnabled()) { - log.info("load script : " + script); - } - - StringBuilder out = new StringBuilder(); - - int nbLines = Scripts.loadScriptContent(script, out); - - String scriptContent = out.toString(); - - if (log.isInfoEnabled()) { - log.info("created script : " + nbLines + " lines."); - } - if (log.isDebugEnabled()) { - log.debug("created script content \n" + script); - } - - loadScript(scriptContent); - } - - public List<Pair<String, String>> getTables() throws SQLException { - - Connection conn = dataSourceConfig.getSQLConnection(); - try { - return getTables(conn, SCHEMAS, EXTRA_TABLES); - } finally { - dataSourceConfig.close(conn); - } - } - - public Set<String> getRoles() throws SQLException { - - Connection conn = dataSourceConfig.getSQLConnection(); - try { - return getRoles(conn); - } finally { - dataSourceConfig.close(conn); - } - } - - protected String createDropScript(Connection conn) throws SQLException { - - List<Pair<String, String>> tables = getTables(conn, SCHEMAS, EXTRA_TABLES); - - if (tables.isEmpty()) { - // no tables - return ""; - } - - if (log.isInfoEnabled()) { - log.info("Will drop " + tables.size() + " table(s)."); - } - - StringBuilder builder = new StringBuilder(); - - addOnTablesForRole(DROP_TABLE_PATTERN, builder, tables, ""); - - for (String schema : SCHEMAS) { - - if (!SCHEMA_PUBLIC.equals(schema)) { - builder.append(String.format(DROP_SCHEMA_PATTERN, schema)); - } - - } - - return builder.toString(); - } - - protected String createSecurityScript(Connection conn) throws SQLException { - if (securityModel == null) { - throw new NullPointerException("securityModel can not be null"); - } - - List<Pair<String, String>> tables = getTables(conn, SCHEMAS, EXTRA_TABLES); - - if (tables.isEmpty()) { - // no tables - return ""; - } - if (log.isInfoEnabled()) { - log.info("Will apply security on " + tables.size() + " table(s)."); - log.info(" - administrateur : " + securityModel.getAdministrateur()); - log.info(" - techniciens : " + securityModel.getTechnicien()); - log.info(" - utilisateurs : " + securityModel.getUtilisateur()); - log.info(" - referentiels : " + securityModel.getReferentiel()); - } - - List<Pair<String, String>> referentielTables = getReferentielTables(tables); - - getDataTables(tables, referentielTables); - - Set<String> allPostgisFunctions = new LinkedHashSet<String>(); - for (String postgisFunction : FUNCTION_NAMES_PREFIXS) { - Set<String> postgisFunctions = getPostgisFunctions(conn, postgisFunction); - allPostgisFunctions.addAll(postgisFunctions); - } - - StringBuilder builder = new StringBuilder(); - - // suppression de tous les droits - { - Set<String> privateRoles = new HashSet<String>(); - privateRoles.add("public"); - privateRoles.addAll(securityModel.getEscapedReferentiel()); - privateRoles.addAll(securityModel.getEscapedUtilisateur()); - privateRoles.addAll(securityModel.getEscapedUnused()); - - String roles = StringUtil.join(privateRoles, ",", true); - - addOnTablesForRole(REVOKE_ON_TABLE_ALL_PATTERN, builder, tables, roles); - addOnSchemaForRole(REVOKE_ON_SCHEMA_ALL_PATTERN, builder, SCHEMAS, roles); - addOnFunctionForRole(REVOKE_ON_FUNCTIONS_PATTERN, builder, allPostgisFunctions, roles); - - } - - // ajout propriétaire - addOnTablesForRole(SET_ON_TABLE_OWNER_PATTERN, builder, tables, securityModel.getEscapedAdministrateur()); - addOnSchemaForRole(GRANT_ON_SCHEMA_ALL_PATTERN, builder, SCHEMAS, securityModel.getEscapedAdministrateur()); - addOnSchemaForRole(GRANT_ON_FUNCTION_PATTERN, builder, allPostgisFunctions, securityModel.getEscapedAdministrateur()); - - // ajout administrateurs - if (CollectionUtils.isNotEmpty(securityModel.getEscapedTechnicien())) { - String roles = StringUtil.join(securityModel.getEscapedTechnicien(), ",", true); - addOnTablesForRole(GRANT_ON_TABLE_ALL_PATTERN, builder, tables, roles); - addOnSchemaForRole(GRANT_ON_SCHEMA_ALL_PATTERN, builder, SCHEMAS, roles); - addOnSchemaForRole(GRANT_ON_FUNCTION_PATTERN, builder, allPostgisFunctions, roles); - } - - // ajout utilisateur - if (CollectionUtils.isNotEmpty(securityModel.getEscapedUtilisateur())) { - String roles = StringUtil.join(securityModel.getEscapedUtilisateur(), ",", true); - addOnTablesForRole(GRANT_ON_TABLE_READ_PATTERN, builder, tables, roles); - addOnSchemaForRole(GRANT_ON_SCHEMA_ALL_PATTERN, builder, SCHEMAS, roles); - addOnSchemaForRole(GRANT_ON_FUNCTION_PATTERN, builder, allPostgisFunctions, roles); - } - - // ajout referentiel - if (CollectionUtils.isNotEmpty(securityModel.getEscapedReferentiel())) { - String roles = StringUtil.join(securityModel.getEscapedReferentiel(), ",", true); - addOnTablesForRole(GRANT_ON_TABLE_READ_PATTERN, builder, referentielTables, roles); - addOnSchemaForRole(GRANT_ON_SCHEMA_ALL_PATTERN, builder, SCHEMAS, roles); - addOnSchemaForRole(GRANT_ON_FUNCTION_PATTERN, builder, allPostgisFunctions, roles); - } - - String result = builder.toString(); - - if (log.isInfoEnabled()) { - log.info("Security script :\n" + result); - } - return result; - } - - protected List<Pair<String, String>> getReferentielTables(Iterable<Pair<String, String>> tables) { - Set<TopiaEntityEnum> types = new HashSet<TopiaEntityEnum>(); - types.addAll(Arrays.asList(Entities.REFERENCE_ENTITIES)); - - List<Pair<String, String>> result = getTables(tables, types, EXTRA_TABLES); - if (log.isInfoEnabled()) { - StringBuilder sb = new StringBuilder(); - sb.append("Detected ").append(result.size()).append(" referentiel tables :"); - for (Pair<String, String> s : result) { - sb.append("\n - ").append(s); - } - log.info(sb.toString()); - } - return result; - } - - protected Set<String> getPostgisFunctions(Connection conn, String functionPattern) throws SQLException { - - final Set<String> result = new LinkedHashSet<String>(); - String sql = String.format("SELECT ns.nspname::text || '.' || p.proname::text || '(' || oidvectortypes(p.proargtypes)::text || ')'" + - " FROM pg_proc p INNER JOIN pg_namespace ns ON (p.pronamespace = ns.oid)" + - " WHERE ns.nspname = 'public' AND p.proname ILIKE '%s%%';", functionPattern); - PreparedStatement sta = - conn.prepareStatement(sql); - try { - ResultSet set = sta.executeQuery(); - - while (set.next()) { - String functionPrototype = set.getString(1); - result.add(functionPrototype); - } - - } finally { - - sta.close(); - } - return result; - - } - - protected List<Pair<String, String>> getDataTables(Collection<Pair<String, String>> tables, - Collection<Pair<String, String>> referentielTables) { - List<Pair<String, String>> result = new ArrayList<Pair<String, String>>(tables); - result.removeAll(referentielTables); - - if (log.isInfoEnabled()) { - StringBuilder sb = new StringBuilder(); - sb.append("Detected ").append(result.size()).append(" data tables :"); - for (Pair<String, String> s : result) { - sb.append("\n - ").append(s); - } - log.info(sb.toString()); - } - return result; - } - - protected List<Pair<String, String>> getTables(Iterable<Pair<String, String>> tables, - Set<TopiaEntityEnum> types, - Set<String> extraTypes) { - List<Pair<String, String>> result = new ArrayList<Pair<String, String>>(); - for (Pair<String, String> t : tables) { - String table = t.getRight(); - String detectedType = null; - for (TopiaEntityEnum type : types) { - String name = type.dbTableName(); - if (table.equalsIgnoreCase(name) || table.startsWith(name + "_")) { - detectedType = name; - break; - } - } - if (detectedType == null) { - for (String extraType : extraTypes) { - if (table.equalsIgnoreCase(extraType)) { - detectedType = extraType; - break; - } - } - } - if (detectedType != null && !result.contains(t)) { - result.add(t); - } - } - Collections.sort(result); - return result; - } - - protected Set<String> getRoles(Connection conn) throws SQLException { - List<String> result = new ArrayList<String>(); - - PreparedStatement sta = - conn.prepareStatement("SELECT rolname FROM pg_catalog.pg_roles ;"); - try { - ResultSet set = sta.executeQuery(); - - while (set.next()) { - String role = set.getString(1); - if (!"postgres".equals(role)) { - result.add(role); - } - } - - } finally { - - sta.close(); - } - - Collections.sort(result); - if (log.isInfoEnabled()) { - StringBuilder sb = new StringBuilder(); - sb.append("Detected ").append(result.size()).append(" roles :"); - for (String s : result) { - sb.append("\n - ").append(s); - } - log.info(sb.toString()); - } - return new HashSet<String>(result); - } - - protected void addOnTablesForRole(String pattern, - StringBuilder builder, - Iterable<Pair<String, String>> tables, - String role) { - - for (Pair<String, String> t : tables) { - builder.append(String.format(pattern, t.getLeft(), t.getRight(), role)); - } - } - - protected void addOnSchemaForRole(String pattern, - StringBuilder builder, - Set<String> schemas, - String role) { - - for (String t : schemas) { - builder.append(String.format(pattern, t, role)); - } - } - - protected void addOnFunctionForRole(String pattern, - StringBuilder builder, - Set<String> functions, - String role) { - - for (String t : functions) { - builder.append(String.format(pattern, t, role)); - } - } - - protected List<Pair<String, String>> getTables(Connection conn, Set<String> schemas, Set<String> extraTables) throws SQLException { - List<Pair<String, String>> result = new ArrayList<Pair<String, String>>(); - - // recuperation des tables sur la base - DatabaseMetaData data = conn.getMetaData(); - ResultSet tables = data.getTables(null, - null, - null, - new String[]{"TABLE"} - ); - - try { - int columnCount = tables.getMetaData().getColumnCount(); - - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - builder.append("\nheader"); - for (int i = 1; i <= columnCount; i++) { - String columnName = tables.getMetaData().getColumnName(i); - builder.append("\n [").append(i).append("] :").append(columnName); - } - log.debug(builder.toString()); - log.debug("fetchSize : " + tables.getFetchSize()); - } - while (tables.next()) { - String schemaName = tables.getString(2); - String tableName = tables.getString(3); - if (log.isDebugEnabled()) { - log.debug(String.format("Discover table named %s", tables)); - } - if (!extraTables.contains(tableName)) { - - if (POSTGIS_TABLES.contains(tableName)) { - continue; - } - - if (schemaName == null || !schemas.contains(schemaName.toUpperCase())) { - continue; - } - - } - - if (log.isDebugEnabled()) { - log.debug(String.format("Keep table: %s", tables)); - } - result.add(Pair.of(schemaName, tableName)); - } - - Collections.sort(result); - return result; - } finally { - tables.close(); - } - } - - protected void loadScript(String scriptContent) throws SQLException { - Connection conn = dataSourceConfig.getSQLConnection(); - try { - if (dataSourceConfig.isShowMigrationSql()) { - if (log.isInfoEnabled()) { - log.info("SQL to execute :\n" + scriptContent); - } - } - Scripts.loadScript(conn, scriptContent); - conn.commit(); - } finally { - dataSourceConfig.close(conn); - } - } - - public void close() { - dataSourceConfig = null; - securityModel = null; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/util/SecurityModel.java b/observe-business/src/main/java/fr/ird/observe/db/util/SecurityModel.java deleted file mode 100644 index b0223aa..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/util/SecurityModel.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.util; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; - -/** - * Le modèle la sécurité à appliquer sur une base postgres - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SecurityModel implements Serializable { - - public static final String PROPERTY_ADMINISTRATEUR = "administrateur"; - - public static final String PROPERTY_ROLE = "role"; - - public static final String PROPERTY_ASSIGNED = "assigned"; - - private static final long serialVersionUID = 1L; - - public static final Function<String, String> ESCAPE_STRING = new Function<String, String>() { - @Override - public String apply(String input) { - return "\"" + input + "\""; - } - }; - - public enum Role { - unused, - referentiel, - utilisateur, - technicien - } - - protected String administrateur; - - protected SortedMap<String, Role> map; - - protected PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - public SecurityModel() { - map = new TreeMap<String, Role>(); - } - - public String getAdministrateur() { - return administrateur; - } - - public Role getRole(String role) { - return map.get(role); - } - - public Set<String> getRole(Role role) { - Set<String> roles = new HashSet<String>(); - for (Map.Entry<String, Role> entry : map.entrySet()) { - if (role.equals(entry.getValue())) { - roles.add(entry.getKey()); - } - } - return roles; - } - - public Set<String> getRole() { - return map.keySet(); - } - - public Set<String> getTechnicien() { - return getRole(Role.technicien); - } - - public Set<String> getUtilisateur() { - return getRole(Role.utilisateur); - } - - public Set<String> getReferentiel() { - return getRole(Role.referentiel); - } - - public Set<String> getEscapedReferentiel() { - Set<String> result = Sets.newHashSet( - Iterables.transform(getReferentiel(), ESCAPE_STRING)); - return result; - } - - public Set<String> getEscapedTechnicien() { - Set<String> result = Sets.newHashSet( - Iterables.transform(getTechnicien(), ESCAPE_STRING)); - return result; - } - - public Set<String> getEscapedUtilisateur() { - Set<String> result = Sets.newHashSet( - Iterables.transform(getUtilisateur(), ESCAPE_STRING)); - return result; - } - - public String getEscapedAdministrateur() { - return ESCAPE_STRING.apply(getAdministrateur()); - } - - public Set<String> getUnused() { - return getRole(Role.unused); - } - - public Set<String> getEscapedUnused() { - Set<String> result = Sets.newHashSet( - Iterables.transform(getUnused(), ESCAPE_STRING)); - return result; - } - - public boolean isRole(Role r, String role) { - return r.equals(getRole(role)); - } - - public void setAdministrateur(String administrateur) { - Object oldvalue = this.administrateur; - this.administrateur = administrateur; - firePropertyChange(PROPERTY_ADMINISTRATEUR, oldvalue, administrateur); - } - - public void init(Iterable<String> role) { - map.clear(); - if (role != null) { - for (String r : role) { - // by default let's say that any role is not used - // (make it quicker then to only give correct access) - map.put(r, Role.unused); - } - } - firePropertyChange(PROPERTY_ROLE, null, getRole()); - firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); - } - - public void setRole(String name, Role role, boolean fire) { - map.put(name, role); - if (fire) { - if (role != null) { - firePropertyChange(role.name(), null, getRole(role)); - } - firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); - } - } - - public void setRole(Iterable<String> roles, Role role) { - for (String r : roles) { - setRole(r, role, false); - } - firePropertyChange(role.name(), null, getRole(role)); - firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); - } - - public int getAssigned() { - int count = 0; - for (Map.Entry<String, Role> entry : map.entrySet()) { - if (entry.getValue() != null) { - count++; - } - } - return count; - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - protected void firePropertyChange(String propertyName, Object newValue) { - firePropertyChange(propertyName, null, newValue); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/util/TopiaExecutor.java b/observe-business/src/main/java/fr/ird/observe/db/util/TopiaExecutor.java deleted file mode 100644 index a318a38..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/util/TopiaExecutor.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.util; - -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.persistence.TopiaEntity; - -/** - * Contrat pour executer quelque chose sur un objet persistant. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface TopiaExecutor<E extends TopiaEntity> { - - void execute(TopiaContext tx, E bean) throws TopiaException; - -} diff --git a/observe-business/src/main/java/fr/ird/observe/db/util/TopiaExecutor2.java b/observe-business/src/main/java/fr/ird/observe/db/util/TopiaExecutor2.java deleted file mode 100644 index 4f34477..0000000 --- a/observe-business/src/main/java/fr/ird/observe/db/util/TopiaExecutor2.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.util; - -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.persistence.TopiaEntity; - -/** - * Contrat pour executer quelque chose sur un objet persistant avec un - * optionel parent. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface TopiaExecutor2<P extends TopiaEntity, E extends TopiaEntity> { - - E execute(TopiaContext tx, P parentBean, E bean) throws TopiaException; - -} diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/LengthWeightParameterDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/LengthWeightParameterDecorator.java deleted file mode 100644 index fbd441f..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/LengthWeightParameterDecorator.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.decorator; - -import fr.ird.observe.entities.referentiel.LengthWeightParameter; -import org.apache.commons.jxpath.JXPathContext; - -import static org.nuiton.i18n.I18n.t; - -/** - * Decorator of {@link LengthWeightParameter}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.4 - */ -public class LengthWeightParameterDecorator extends ObserveDecorator<LengthWeightParameter> { - - private static final long serialVersionUID = 1L; - - private final String libelle; - - public LengthWeightParameterDecorator(String libelle) throws IllegalArgumentException, NullPointerException { - super(LengthWeightParameter.class, - "${gender}$s##${ocean/" + libelle + "}$s##${species/scientificLabel}$s##" + - t("observe.common.lengthWeightFormula") + " ${lengthWeightFormula}$s" - ); - this.libelle = libelle; - } - - @SuppressWarnings({"unchecked"}) - @Override - protected Comparable<Comparable<?>> getTokenValue( - JXPathContext jxcontext, String token) { - Object value; -// if (token.equals("ocean/" + libelle)) { -// try { -// value = super.getTokenValue(jxcontext, -// token); -// } catch (JXPathNotFoundException e) { -// value = t("observe.common.inconnu"); -// } -// value = t("observe.common.ocean") + ' ' + value; -// } else { - - value = super.getTokenValue(jxcontext, token); - if (token.equals("species/scientificLabel") - && "xx".equals(value)) { - value = super.getTokenValue(jxcontext, - "species/" + - libelle); - } - if (token.equals("sex")) { - value = super.getTokenValue(jxcontext, - "sex/" + - libelle); - value = t("observe.common.sex") + ' ' + - value; - } -// } - return (Comparable<Comparable<?>>) value; - } - - @Override - protected Comparable<?> getDefaultUndefinedValue(String token) { - if (token.startsWith("ocean")) { - return t("observe.common.inconnu"); - } - return super.getDefaultUndefinedValue(token); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/NonTargetCatchDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/NonTargetCatchDecorator.java deleted file mode 100644 index f7cf000..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/NonTargetCatchDecorator.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.decorator; - -import fr.ird.observe.entities.seine.NonTargetCatch; -import org.apache.commons.jxpath.JXPathContext; - -/** - * Decorator of {@link NonTargetCatch}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.4 - */ -public class NonTargetCatchDecorator extends ObserveDecorator<NonTargetCatch> { - - private static final long serialVersionUID = 1L; - - private final String libelle; - - public NonTargetCatchDecorator(String libelle) { - super(NonTargetCatch.class, - "${species/scientificLabel}$s##${speciesFate/" + libelle + "}$s" - ); - this.libelle = libelle; - } - - @Override - protected Comparable<Comparable<?>> getTokenValue(JXPathContext jxcontext, - String token) { - Comparable<Comparable<?>> value = super.getTokenValue(jxcontext, token); - if (token.equals("species/scientificLabel") && - "xx".equals(String.valueOf(value))) { - value = super.getTokenValue(jxcontext, "species/" + libelle); - } - return value; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/NonTargetLengthDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/NonTargetLengthDecorator.java deleted file mode 100644 index 068c043..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/NonTargetLengthDecorator.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.decorator; - -import fr.ird.observe.entities.seine.NonTargetLength; -import org.apache.commons.jxpath.JXPathContext; - -/** - * Decorator of {@link NonTargetLength}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.4 - */ -public class NonTargetLengthDecorator extends ObserveDecorator<NonTargetLength> { - - private static final long serialVersionUID = 1L; - - private final String libelle; - - public NonTargetLengthDecorator(String libelle) throws IllegalArgumentException, NullPointerException { - super(NonTargetLength.class, - "${species/scientificLabel}$s##${length}$f##${gender}$s" - ); - this.libelle = libelle; - } - - @SuppressWarnings({"unchecked"}) - @Override - protected Comparable<Comparable<?>> getTokenValue( - JXPathContext jxcontext, String token) { - Comparable<?> value = - super.getTokenValue(jxcontext, token); - if (token.equals("species/scientificLabel") && - "xx".equals(value)) { - value = super.getTokenValue(jxcontext, "species/" + libelle); - } - if ("sex".equals(token)) { - value = super.getTokenValue(jxcontext, "sex/" + libelle); - } - return (Comparable<Comparable<?>>) value; - } - - -} diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/ObjectObservedSpeciesDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/ObjectObservedSpeciesDecorator.java deleted file mode 100644 index c19aa37..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/ObjectObservedSpeciesDecorator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.decorator; - -import fr.ird.observe.entities.seine.ObjectObservedSpecies; -import org.apache.commons.jxpath.JXPathContext; - -/** - * Decorator of {@link ObjectObservedSpecies}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.4 - */ -public class ObjectObservedSpeciesDecorator extends ObserveDecorator<ObjectObservedSpecies> { - - private static final long serialVersionUID = 1L; - - private final String libelle; - - public ObjectObservedSpeciesDecorator(String libelle) { - super(ObjectObservedSpecies.class, - "${species/scientificLabel}$s##${speciesStatus/" + libelle + "}$s##${count}$d" - ); - this.libelle = libelle; - } - - @Override - protected Comparable<Comparable<?>> getTokenValue(JXPathContext jxcontext, String token) { - Comparable<Comparable<?>> value = super.getTokenValue(jxcontext, token); - if (token.equals("species/scientificLabel") && "xx".equals(String.valueOf(value))) { - value = super.getTokenValue(jxcontext, "species/" + libelle); - } - return value; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/ObserveDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/ObserveDecorator.java deleted file mode 100644 index d6f46ab..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/ObserveDecorator.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.decorator; - -import org.apache.commons.jxpath.JXPathContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.MultiJXPathDecorator; - -import static org.nuiton.i18n.I18n.t; - -/** - * Abstract decorator for any complex decorator. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.4 - */ -public abstract class ObserveDecorator<E> extends MultiJXPathDecorator<E> implements Cloneable { - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ObserveDecorator.class); - - public static final String DEFAULT_SEPARATOR = "##"; - - public static final String DEFAULT_SEPARATOR_REPLACEMENT = " - "; - - protected ObserveDecorator(Class<E> internalClass, String expression) { - super(internalClass, expression, DEFAULT_SEPARATOR, - DEFAULT_SEPARATOR_REPLACEMENT); - } - - - @Override - public final Object clone() throws CloneNotSupportedException { - Object clone = super.clone(); - return clone; - } - - protected Comparable<Comparable<?>> getTokenValue(JXPathContext jxcontext, - String token) { - // assume all values are comparable - Comparable<Comparable<?>> value; - try { - value = (Comparable<Comparable<?>>) jxcontext.getValue(token); - if (value == null) { - value = (Comparable<Comparable<?>>) getDefaultNullValue(token); - } - - } catch (Exception e) { - value = (Comparable<Comparable<?>>) getDefaultUndefinedValue(token); - } - - return value; - } - - protected Comparable<?> getDefaultUndefinedValue(String token) { - if (log.isWarnEnabled()) { - log.warn("No defined value for token [" + token + "]"); - } - return t("observe.common.none"); - } - - protected Comparable<?> getDefaultNullValue(String token) { - if (log.isWarnEnabled()) { - log.warn("Null value for token [" + token + "]"); - } - return t("observe.common.none"); - } - - -} diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/ReferenceDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/ReferenceDecorator.java deleted file mode 100644 index d6e0fe3..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/ReferenceDecorator.java +++ /dev/null @@ -1,48 +0,0 @@ -package fr.ird.observe.decorator; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.entities.referentiel.ReferenceEntity; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 7/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.6 - */ -public class ReferenceDecorator<R extends ReferenceEntity> extends ObserveDecorator<R> { - - private static final long serialVersionUID = 1L; - - public ReferenceDecorator(Class<R> type, String expression) { - super(type, expression); - } - - @Override - protected Comparable<?> getDefaultNullValue(String token) { - return ReferenceEntity.PROPERTY_CODE.equals(token) ? t("observe.common.nocode") : super.getDefaultNullValue(token); - } - -} \ No newline at end of file diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/SpeciesDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/SpeciesDecorator.java deleted file mode 100644 index f5daae2..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/SpeciesDecorator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.decorator; - -import fr.ird.observe.entities.referentiel.Species; -import org.apache.commons.jxpath.JXPathContext; - -import static org.nuiton.i18n.I18n.n; - -/** - * Decorator of {@link Species}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.4 - */ -public class SpeciesDecorator extends ObserveDecorator<Species> { - - private static final long serialVersionUID = 1L; - - private final String libelle; - - static { - - // pour avoir les traduction sur le nom de la propriété - - n("observe.common.faoCode"); - n("observe.common.species/scientificLabel"); - n("observe.common.scientificLabel"); - n("observe.common.homeId"); - - - } - - - public SpeciesDecorator(String libelle, String oldCode) { - super(Species.class, - "${faoCode}$s##${scientificLabel}$s##" + oldCode + " ${homeId}$s" - ); - this.libelle = libelle; - } - - @Override - protected Comparable<Comparable<?>> getTokenValue(JXPathContext jxcontext, String token) { - Comparable<?> value; - value = super.getTokenValue(jxcontext, token); - if (token.equals(Species.PROPERTY_SCIENTIFIC_LABEL) && "xx".equals(value)) { - value = super.getTokenValue(jxcontext, libelle); - } - return (Comparable<Comparable<?>>) value; - } - -} diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/TripLonglineDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/TripLonglineDecorator.java deleted file mode 100644 index 9a5e7ea..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/TripLonglineDecorator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.decorator; - -import fr.ird.observe.entities.longline.TripLongline; - -/** - * Decorator of {@link TripLongline}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class TripLonglineDecorator extends ObserveDecorator<TripLongline> { - - private static final long serialVersionUID = 1L; - - public TripLonglineDecorator(String libelle) throws IllegalArgumentException, NullPointerException { - super(TripLongline.class, - "${startDate}$td/%1$tm/%1$tY##${endDate}$td/%2$tm/%2$tY##${vessel/" + libelle + "}$s##${observerLabel}$s" - ); - } - -} diff --git a/observe-business/src/main/java/fr/ird/observe/decorator/TripSeineDecorator.java b/observe-business/src/main/java/fr/ird/observe/decorator/TripSeineDecorator.java deleted file mode 100644 index a6d8a0b..0000000 --- a/observe-business/src/main/java/fr/ird/observe/decorator/TripSeineDecorator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.decorator; - -import fr.ird.observe.entities.seine.TripSeine; - -/** - * Decorator of {@link TripSeine}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.4 - */ -public class TripSeineDecorator extends ObserveDecorator<TripSeine> { - - private static final long serialVersionUID = 1L; - - public TripSeineDecorator(String libelle) throws IllegalArgumentException, NullPointerException { - super(TripSeine.class, - "${startDate}$td/%1$tm/%1$tY##${endDate}$td/%2$tm/%2$tY##${vessel/" + libelle + "}$s##${observerLabel}$s" - ); - } - -} diff --git a/observe-business/src/main/java/fr/ird/observe/gps/GPSFileReader.java b/observe-business/src/main/java/fr/ird/observe/gps/GPSFileReader.java deleted file mode 100644 index 525791a..0000000 --- a/observe-business/src/main/java/fr/ird/observe/gps/GPSFileReader.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.gps; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; -import org.xmlpull.v1.XmlPullParserFactory; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * Classe responsable de la construction du modèle {@link GPSRoute} à partir - * d'un fichier de traces GPS au format <code>GPX</code>. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class GPSFileReader { - - /** log */ - private static final Log log = LogFactory.getLog(GPSFileReader.class); - - public static final String ROUTE_TAG = "trk"; - - public static final String SEGMENT_TAG = "trkseg"; - - public static final String POINT_TAG = "trkpt"; - - public static final String TIME_TAG = "time"; - - public static final String SPEED_TAG = "speed"; - - public static final String LATITUDE_ATTR = "lat"; - - public static final String LONGITUDE_ATTR = "lon"; - - /** le fichier à importer */ - protected final File source; - - /** le délai en minutes acceptable entre deux points */ - protected final int maxDelay; - - /** la vitesse maximum autorisée entre 2 points en noeud */ - protected final float maxSpeed; - - protected final GPSService service; - - public GPSFileReader(GPSService service, - File source, - int maxDelay, - float maxSpeed) { - this.service = service; - this.source = source; - this.maxDelay = maxDelay; - this.maxSpeed = maxSpeed; - } - - public GPSRoute read() throws Exception { - if (source == null) { - throw new NullPointerException("la source ne doit pas être nulle"); - } - if (!source.exists() || !source.isFile()) { - throw new IllegalArgumentException("le fichier source '" + source + "' n'existe pas ou n'est pas un fichier"); - } - - GPSRoute model = new GPSRouteImpl(); - - XmlPullParserFactory factory = XmlPullParserFactory.newInstance( - System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); - factory.setNamespaceAware(true); - XmlPullParser xpp = factory.newPullParser(); - FileReader fileReader = new FileReader(source); - - try { - xpp.setInput(fileReader); - - parseFile(xpp, model); - } finally { - fileReader.close(); - } - - return model; - } - - /** - * Détecte sur l'ensemble des points de la route ceux qui sont acceptables, - * c'est à dire que l'on accepte uniquement les points dont les intervalles - * de temps ne dépassent pas {@link #maxDelay}. - * <p/> - * Les intervalles de poinbts acceptables seront contenus dans {@link - * GPSRoute#acceptedInterval}, les intervalles rejetés seront sauvés dans - * {@link GPSRoute#rejectedInterval} - * - * @param route la route à traiter - */ - public void detectIntervals(GPSRoute route) { - if (log.isInfoEnabled()) { - log.info("starting... for " + this); - } - List<GPSPointInterval> acceptedList = new ArrayList<GPSPointInterval>(); - List<GPSPointInterval> rejectedList = new ArrayList<GPSPointInterval>(); - GPSPointInterval currentAccepted = null; - GPSPointInterval currentRejected = null; - GPSPoint previous = null; - // le delai acceptable entre deux points en millisecondes - long delay = getMaxSpeedAsMilliSecondes(); - - for (GPSPoint p : route.getPoint()) { - if (log.isTraceEnabled()) { - log.trace("test point " + p); - } - if (previous == null) { - // premeir point rencontré, rien à faire - previous = p; - continue; - } - long delta = service.getDelay(previous, p); - if (delta <= delay) { - // le point courant est acceptable - // on l'enregistre dans l'intervalle accepté - if (log.isDebugEnabled()) { - log.debug("accepted point: " + p + ", delta: " + delta); - } - - if (currentRejected != null) { - // on etait sur un intervalle de rejet - // il faut le fermer et l'enregister dans le modèle - rejectedList.add(currentRejected); - currentRejected = null; - } - if (currentAccepted == null) { - currentAccepted = new GPSPointIntervalImpl(); - currentAccepted.setPoint(new ArrayList<GPSPoint>()); - currentAccepted.addPoint(previous); - } - currentAccepted.addPoint(p); - previous = p; - continue; - } - - // le point courant n'est pas acceptable - // on l'enregistre dans l'intervalle courant de rejet - - if (log.isDebugEnabled()) { - log.debug("rejected point: " + p + ", delta: " + delta); - } - if (currentAccepted != null) { - // on était sur un intervall accepté, on doit le fermer - // et l'enregistre dans le modèle - acceptedList.add(currentAccepted); - currentAccepted = null; - } - if (currentRejected == null) { - // nouvelle intervalle de rejet - currentRejected = new GPSPointIntervalImpl(); - currentRejected.setPoint(new ArrayList<GPSPoint>()); - currentRejected.addPoint(previous); - } - currentRejected.addPoint(p); - previous = p; - } - - if (currentAccepted != null) { - // ajout de l'intervalle accepté - acceptedList.add(currentAccepted); - } - - if (currentRejected != null) { - // ajout de l'intervalle rejeté - rejectedList.add(currentRejected); - } - - // on enregistre les intervalles dans le modèle - if (!acceptedList.isEmpty()) { - route.setAcceptedInterval(acceptedList); - } - if (!rejectedList.isEmpty()) { - route.setRejectedInterval(rejectedList); - } - - } - - @Override - public String toString() { - String result = new ToStringBuilder(this).append("source", source). - append("maxDelay (ms)", getMaxSpeedAsMilliSecondes()). - append("maxSpeed (nd)", maxSpeed). - toString(); - return result; - } - - protected long getMaxSpeedAsMilliSecondes() { - return maxDelay * 60 * 1000; - } - - /** - * Parse le fichier xml donné et construit le modèle. - * <p/> - * Pour le moment on se limite à traiter le premier segment - * (<code>trkseg</code>) de la première route (<code>trk</code>). - * <p/> - * Lors de la découverte des points, on ne retient pas les points dont la - * vitesse par rapport au précédent point dépasse {@link - * #getMaxSpeedAsMilliSecondes()}. - * - * @param xpp le parser xml - * @param model le model à remplir - * @throws IOException - * @throws XmlPullParserException - * @throws ParseException - */ - protected void parseFile(XmlPullParser xpp, - GPSRoute model) throws IOException, XmlPullParserException, ParseException { - List<GPSPoint> points = new ArrayList<GPSPoint>(); - GPSPoint previousPoint = null; - GPSPoint currentPoint = null; - boolean findRoute = false; - boolean findSegment = false; - int elementType; - - String localName; - - if (xpp.getEventType() == XmlPullParser.START_DOCUMENT) { - xpp.next(); - } - - // recherche du premier segment de la première route - while (xpp.next() != XmlPullParser.END_DOCUMENT) { - // nouveau tag - localName = xpp.getName(); - if (ROUTE_TAG.equals(localName)) { - findRoute = true; - break; - } - } - if (!findRoute) { - // aucune route trouvée - return; - } - while ((elementType = xpp.next()) != XmlPullParser.END_DOCUMENT) { - // nouveau tag - localName = xpp.getName(); - if (SEGMENT_TAG.equals(localName)) { - findSegment = true; - break; - } - } - if (!findSegment) { - // aucun segment trouvé - return; - } - - String content; - - //format de type : 2007-11-09T04:54:27.000Z - DateFormat df = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSSS'Z'"); - - Float f; - while ((elementType = xpp.next()) != XmlPullParser.END_DOCUMENT) { - localName = xpp.getName(); - if (elementType == XmlPullParser.START_TAG) { - // debut d'un tag - if (POINT_TAG.equals(localName)) { - // debut d'un point - currentPoint = new GPSPointImpl(); - content = xpp.getAttributeValue(null, LATITUDE_ATTR); - f = Float.valueOf(content); - currentPoint.setLatitude(f); - content = xpp.getAttributeValue(null, LONGITUDE_ATTR); - f = Float.valueOf(content); - currentPoint.setLongitude(f); - continue; - } - if (TIME_TAG.equals(localName)) { - // tag de time - content = xpp.nextText(); - - Date d = df.parse(content); - currentPoint.setTime(d); - continue; - } - if (SPEED_TAG.equals(localName)) { - // tag de vitesse - content = xpp.nextText(); - f = Float.valueOf(content); - currentPoint.setVitesse(f); - continue; - } - - // les autres tags en ouverture ne sont pas traités pour le moment - continue; - } - if (elementType == XmlPullParser.END_TAG) { - // fin d'un tag - if (POINT_TAG.equals(localName)) { - // fin d'un point - boolean canAccept = true; - if (previousPoint != null) { - // on vérifie que la vitesse entrez les deux points - // est acceptable - float speed = service.getSpeed(previousPoint, currentPoint); - if (speed > maxSpeed) { - // on ne peut pas accepter ce point - canAccept = false; - } - } - if (canAccept) { - // le point est acceptable, on le conserve - points.add(currentPoint); - // et il passe en nouveau point de reference - previousPoint = currentPoint; - } - currentPoint = null; - continue; - } - if (SEGMENT_TAG.equals(localName)) { - // fin du segment - // on a terminé la lecture du premier segment - // on peut quitter le parsing - break; - } - } - } - model.setPoint(points); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/gps/GPSService.java b/observe-business/src/main/java/fr/ird/observe/gps/GPSService.java deleted file mode 100644 index b33ae29..0000000 --- a/observe-business/src/main/java/fr/ird/observe/gps/GPSService.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.gps; - -import java.io.File; - -/** - * Service de manipulation GPS. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class GPSService { - - /** - * Construit la route gps à partir d'un fichier gps donnée et des deux - * indicateurs {@code maxDelay} et {@code maxSpeed} et la retourne. - * - * @param file le fichier contenant les données gps - * @param maxDelay le maximum de temps entre 2 points - * @param maxSpeed le vitesse maximale en 2 points - * @return la route gps calculée - * @throws Exception pour tout probleme lors la construction de la route - */ - public GPSRoute buildRoute(File file, - int maxDelay, - float maxSpeed) throws Exception { - GPSFileReader reader = new GPSFileReader(this, file, maxDelay, maxSpeed); - GPSRoute r = reader.read(); - reader.detectIntervals(r); - return r; - } - - /** - * Calcule la distance entre deux points (en kilometres). - * <p/> - * Il s'agit d'une approxiation utilisant la méthode d'orthodromie. - * <p/> - * http://fr.wikipedia.org/wiki/Orthodromie - * <p/> - * d = R * arccos(cos(lat1) * cos(lat2) *cos(long2 - long1) + sin(lat1) - * *sin(lat2)) - * - * @param p0 le premier point - * @param p1 le second point - * @return la distance calculée entre les deux points en kilometres. - */ - public double getDistanceInKm(GPSPoint p0, GPSPoint p1) { - double d = GpsPoints.getDistanceInKm(p0, p1); - return d; - } - - /** - * Calcule la distance entre deux points (en miles nautique). - * <p/> - * Il s'agit d'une approxiation utilisant la méthode d'orthodromie. - * <p/> - * http://fr.wikipedia.org/wiki/Orthodromie - * <p/> - * d = R * arccos(cos(lat1) * cos(lat2) *cos(long2 - long1) + sin(lat1) - * *sin(lat2)) - * - * @param p0 le premier point - * @param p1 le second point - * @return la distance calculée entre les deux points en noeud. - */ - public double getDistanceInMile(GPSPoint p0, GPSPoint p1) { - double d = GpsPoints.getDistanceInMile(p0, p1); - return d; - } - - /** - * Calcule la vitesse entre deux points (en noeud). - * - * @param p0 le premier point - * @param p1 le second point - * @return la vitesse calculée entre les deux points en noeud. - */ - public float getSpeed(GPSPoint p0, GPSPoint p1) { - float d = GpsPoints.getSpeed(p0, p1); - return d; - - } - - /** - * Calcule le temps écoulé entre deux points (en millisecondes). - * - * @param p0 le premier point - * @param p1 le second point - * @return le temps écoulé entre les deux points en millisecondes. - */ - public long getDelay(GPSPoint p0, GPSPoint p1) { - return GpsPoints.getDelay(p0, p1); - } - -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/ReportBuilder.java b/observe-business/src/main/java/fr/ird/observe/report/ReportBuilder.java deleted file mode 100644 index 6eec032..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/ReportBuilder.java +++ /dev/null @@ -1,490 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report; - - -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportExecute; -import fr.ird.observe.report.model.ReportOperation; -import fr.ird.observe.report.model.ReportRequest; -import fr.ird.observe.report.model.ReportVariable; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.SortedProperties; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.ServiceLoader; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Classe responsable de la construction d'un report à partir de sa définition - * lue dans un fichier de propriétés. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ReportBuilder { - - public static final Pattern REPORT_DEFINITION_PATTERN = Pattern.compile("report.(\\w+).name"); - - public static final String REQUEST_PREFIX = "request."; - - public static final String OPERATION_PREFIX = "operations."; - - public static final String VARIABLE_PREFIX = "variable."; - - public static final String REPEAT_VARIABLE_PREFIX = "repeatVariable."; - - /** Logger */ - private static final Log log = LogFactory.getLog(ReportBuilder.class); - - /** les propriétés chargées par le builder pour construire les reports */ - protected Properties properties; - - /** la liste des lastName sde reports connus par le système */ - protected List<String> reportNames; - - /** les operations connues par le système */ - protected static Map<String, Class<?>> operations; - - public static Map<String, Class<?>> getOperations() { - if (operations == null) { - operations = new TreeMap<String, Class<?>>(); - ServiceLoader<ReportOperation> loader = - ServiceLoader.load(ReportOperation.class); - for (ReportOperation op : loader) { - if (log.isInfoEnabled()) { - log.info("Detected operations : " + op.getOperationName()); - } - operations.put(op.getOperationName(), op.getClass()); - } - } - return operations; - } - - public static ReportOperation newOperation(String operationsName) { - Class<?> operationsType = getOperations().get(operationsName); - if (operationsType == null) { - throw new IllegalArgumentException("No such operations [" + operationsName + "], available operationss : " + getOperations().keySet()); - } - try { - Object result = operationsType.newInstance(); - return (ReportOperation) result; - } catch (Exception e) { - throw new IllegalStateException("Could not instanciate operations [" + operationsType + "]", e); - } - } - - public List<String> getReportNames() { - return reportNames; - } - - public List<Report> load(URL definition) throws IOException { - properties = new SortedProperties(); - InputStream in = definition.openStream(); - try { - properties.load(in); - } finally { - in.close(); - } - - reportNames = detectReportNames(); - if (log.isInfoEnabled()) { - log.info("Detected report names : " + reportNames); - } - - List<Report> reports = new ArrayList<Report>(); - for (String reportName : reportNames) { - Report report = build(reportName); - reports.add(report); - } - - return reports; - } - - - protected List<String> detectReportNames() { - List<String> reportNames = new ArrayList<String>(); - Enumeration<Object> keys = properties.keys(); - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - Matcher matcher = REPORT_DEFINITION_PATTERN.matcher(key); - if (!matcher.matches()) { - - // pas de match - continue; - } - String reportName = matcher.group(1); - if (log.isInfoEnabled()) { - log.info("Discover a new report : " + reportName); - } - reportNames.add(reportName); - } - return reportNames; - } - - protected Report build(String reportName) { - - Map<String, String> dico = detectReportProperties(reportName); - - if (log.isDebugEnabled()) { - log.debug("Will build report [" + reportName + "] with " + dico.size() + " properties (" + dico + ")."); - } - - String name = getValue(dico, "name").trim(); - String description = getValue(dico, "description").trim(); - String rows = getValue(dico, "rows"); - String columns = getValue(dico, "columns"); - String[] rowHeaders = rows == null ? null : rows.split(","); - if (rowHeaders != null) { - for (int i = 0; i < rowHeaders.length; i++) { - String rowHeader = rowHeaders[i]; - rowHeaders[i] = rowHeader.trim(); - } - } - String[] columnHeaders = columns == null ? null : columns.split(","); - if (columnHeaders != null) { - for (int i = 0; i < columnHeaders.length; i++) { - String columnHeader = columnHeaders[i]; - columnHeaders[i] = columnHeader.trim(); - } - } - ReportRequest[] requests = getRequests(reportName, dico); - ReportOperation[] operationss = getOperations(reportName, dico); - ReportVariable[] variables = getVariables(reportName, dico); - ReportVariable[] repeatVariables = getRepeatVariables(reportName, dico); - - // a la fin il ne devrait plus y avoir de propriétés pour le report - if (!dico.isEmpty()) { - if (log.isWarnEnabled()) { - log.warn("Il reste des propriétés non utilisées pour le report [" + reportName + "] : " + dico); - } - } - - Report report = new Report(reportName, - name, - description, - rowHeaders, - columnHeaders, - operationss, - variables, - repeatVariables, - requests - ); - - return report; - } - - protected Map<String, String> detectReportProperties(String reportName) { - - Map<String, String> dico = new TreeMap<String, String>(); - - // pour chaque report, on récupère ses informations - String reportKeyPrefix = "report." + reportName + "."; - int reportKeyPrefixLength = reportKeyPrefix.length(); - - Enumeration<Object> keys = properties.keys(); - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - if (!key.startsWith(reportKeyPrefix)) { - // pas de match - continue; - } - String realKey = key.substring(reportKeyPrefixLength); - dico.put(realKey, (String) properties.get(key)); - } - - return dico; - } - - protected ReportRequest[] getRequests(String reportName, Map<String, String> dico) { - - Map<Integer, String> requestDico = new TreeMap<Integer, String>(); - Map<Integer, String> requestRepeatDico = new TreeMap<Integer, String>(); - Iterator<Map.Entry<String, String>> itr = dico.entrySet().iterator(); - while (itr.hasNext()) { - Map.Entry<String, String> entry = itr.next(); - String key = entry.getKey(); - if (!key.startsWith(REQUEST_PREFIX)) { - - continue; - } - String REQUEST_REPEAT_SUFFIX = ".repeat"; - if (key.endsWith(REQUEST_REPEAT_SUFFIX)) { - - // definition d'un repeat - String request = entry.getValue(); - String requestId = key.substring(REQUEST_PREFIX.length()); - requestId = requestId.substring(0, requestId.length() - REQUEST_REPEAT_SUFFIX.length()); - Integer id = Integer.valueOf(requestId); - if (log.isInfoEnabled()) { - log.info("Detects a request repeat [" + reportName + ":" + id + "] = " + request); - } - requestRepeatDico.put(id, request); - itr.remove(); - continue; - } - String request = entry.getValue(); - String requestId = key.substring(REQUEST_PREFIX.length()); - Integer id = Integer.valueOf(requestId); - if (log.isDebugEnabled()) { - log.debug("Detects a request [" + reportName + ":" + id + "] = " + request); - } - requestDico.put(id, request); - itr.remove(); - - } - - // On trie les request - List<Integer> ids = new ArrayList<Integer>(requestDico.keySet()); - Collections.sort(ids); - - // on construit (dans le bon ordre la liste des requetes) - List<ReportRequest> result = new ArrayList<ReportRequest>(); - for (Integer id : ids) { - - String requestDef = requestDico.get(id); - String requestRepeatDef = requestRepeatDico.get(id); - - ReportRequest def = getRequest(requestDef, requestRepeatDef); - if (log.isInfoEnabled()) { - log.info("Detects a request : " + def); - } - result.add(def); - - } - return result.toArray(new ReportRequest[result.size()]); - } - - protected ReportRequest getRequest(String requestDef, - String requestRepeatDef) { - - String[] parts = requestDef.split("\\|"); - if (parts.length != 3) { - throw new IllegalArgumentException("La définition de la requete doit etre de type 'X,Y|layout|hql' mais est : " + requestDef); - } - String[] coords = parts[0].split(","); - String layout = parts[1]; - String hql = parts[2]; - - if (coords.length != 2) { - throw new IllegalArgumentException("La définition des coordonées doit etre de type 'X,Y' mais est : " + parts[0]); - } - - int x = Integer.valueOf(coords[0]); - int y = Integer.valueOf(coords[1]); - ReportRequest.RequestLayout realLayout = ReportRequest.RequestLayout.valueOf(layout); - - ReportRequest.RequestRepeat repeat = null; - if (requestRepeatDef != null) { - - // il y a un repeat - String[] repeatParts = requestRepeatDef.split("\\|"); - if (repeatParts.length != 2) { - throw new IllegalArgumentException("La définition d'un repéteur de requete doit etre de type 'repeatName|layout' mais est : " + requestRepeatDef); - } - String repeatName = repeatParts[0].trim(); - String repeatLayout = repeatParts[1].trim(); - ReportRequest.RequestLayout realRepeatLayout = - ReportRequest.RequestLayout.valueOf(repeatLayout); - repeat = new ReportRequest.RequestRepeat(repeatName, realRepeatLayout); - - } - ReportRequest def = new ReportRequest(realLayout, x, y, hql, repeat); - return def; - } - - protected ReportOperation[] getOperations(String reportName, Map<String, String> dico) { - - Map<Integer, String> requestDico = new TreeMap<Integer, String>(); - Iterator<Map.Entry<String, String>> itr = dico.entrySet().iterator(); - while (itr.hasNext()) { - Map.Entry<String, String> entry = itr.next(); - String key = entry.getKey(); - if (!key.startsWith(OPERATION_PREFIX)) { - - continue; - } - String operations = entry.getValue(); - String requestId = key.substring(OPERATION_PREFIX.length()); - Integer id = Integer.valueOf(requestId); - if (log.isDebugEnabled()) { - log.debug("Detects a operations [" + reportName + ":" + id + "] = " + operations); - } - requestDico.put(id, operations); - itr.remove(); - } - - // On trie les request - List<Integer> ids = new ArrayList<Integer>(requestDico.keySet()); - Collections.sort(ids); - - // on construit (dans le bon ordre la liste des requetes) - List<ReportOperation> result = new ArrayList<ReportOperation>(); - for (Integer id : ids) { - - String operationsDef = requestDico.get(id); - - ReportOperation def = getOperation(operationsDef); - if (log.isInfoEnabled()) { - log.info("Detects a operations : " + def); - } - result.add(def); - } - return result.toArray(new ReportOperation[result.size()]); - } - - protected ReportVariable[] getVariables(String reportName, Map<String, String> dico) { - List<ReportVariable> result = new ArrayList<ReportVariable>(); - Iterator<Map.Entry<String, String>> itr = dico.entrySet().iterator(); - List<String> ids = new ArrayList<String>(); - while (itr.hasNext()) { - Map.Entry<String, String> entry = itr.next(); - String key = entry.getKey(); - if (!key.startsWith(VARIABLE_PREFIX)) { - - continue; - } - String operations = entry.getValue(); - String id = key.substring(VARIABLE_PREFIX.length()); - - // on interdit la surcharge d'une variable déjà trouvée pour le report - if (ids.contains(id)) { - throw new IllegalArgumentException("La variable " + id + " est déjà définie pour le report " + reportName); - } - - // on interdit l'utilisation de la variable tripId - if (ReportExecute.TRIP_ID_VARIABLE.equals(id)) { - throw new IllegalArgumentException("La variable tripId n'est pas utilisable (c'est uen variable réservée) pour le report " + reportName); - } - ids.add(id); - String[] parts = operations.split("\\|"); - - if (parts.length != 2) { - throw new IllegalArgumentException("La définition d'une variable doit etre de la forme 'type|hql' mais est : " + operations); - } - String typeStr = parts[0].trim(); - String request = parts[1].trim(); - Class<?> type = null; - try { - type = Class.forName(typeStr); - } catch (ClassNotFoundException eee) { - throw new IllegalArgumentException("Le type " + type + " n'est pas connu", eee); - } - ReportVariable variable = new ReportVariable(id, type, request); - if (log.isInfoEnabled()) { - log.info("Detects a variable : [" + reportName + ":" + variable.getName() + "] = " + variable.getRequest() + " (type = " + variable.getType().getName() + ")"); - } - result.add(variable); - itr.remove(); - } - return result.toArray(new ReportVariable[result.size()]); - } - - protected ReportVariable[] getRepeatVariables(String reportName, Map<String, String> dico) { - List<ReportVariable> result = new ArrayList<ReportVariable>(); - Iterator<Map.Entry<String, String>> itr = dico.entrySet().iterator(); - List<String> ids = new ArrayList<String>(); - while (itr.hasNext()) { - Map.Entry<String, String> entry = itr.next(); - String key = entry.getKey(); - if (!key.startsWith(REPEAT_VARIABLE_PREFIX)) { - - continue; - } - String operations = entry.getValue(); - String id = key.substring(REPEAT_VARIABLE_PREFIX.length()); - - // on interdit la surcharge d'une variable déjà trouvée pour le report - if (ids.contains(id)) { - throw new IllegalArgumentException("La variable de répétition " + id + " est déjà définie pour le report " + reportName); - } - - // on interdit l'utilisation de la variable tripId - if (ReportExecute.TRIP_ID_VARIABLE.equals(id)) { - throw new IllegalArgumentException("La variable de répétition tripId n'est pas utilisable (c'est uen variable réservée) pour le report " + reportName); - } - ids.add(id); - String[] parts = operations.split("\\|"); - - if (parts.length != 2) { - throw new IllegalArgumentException("La définition d'une variable de répétition doit etre de la forme 'type|hql' mais est : " + operations); - } - String typeStr = parts[0].trim(); - String request = parts[1].trim(); - Class<?> type = null; - try { - type = Class.forName(typeStr); - } catch (ClassNotFoundException eee) { - throw new IllegalArgumentException("Le type " + type + " n'est pas connu", eee); - } - ReportVariable variable = new ReportVariable(id, type, request); - if (log.isInfoEnabled()) { - log.info("Detects a variable : [" + reportName + ":" + variable.getName() + "] = " + variable.getRequest() + " (type = " + variable.getType().getName() + ")"); - } - result.add(variable); - itr.remove(); - } - return result.toArray(new ReportVariable[result.size()]); - } - - protected ReportOperation getOperation(String operationsDef) { - - // pour le moment, une operations n'a qu'une seule valeur : celle - // du lastName de l'opération - String operationsName = operationsDef; - - ReportOperation def = newOperation(operationsName); - return def; - } - - protected String getValue(Map<String, String> dico, String key) { - - String value = dico.get(key); - if (value != null) { - dico.remove(key); - } - return value; - } - - public void clear() { - if (reportNames != null) { - reportNames.clear(); - reportNames = null; - } - if (properties != null) { - properties.clear(); - properties = null; - } - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/DataMatrix.java b/observe-business/src/main/java/fr/ird/observe/report/model/DataMatrix.java deleted file mode 100644 index cbed640..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/DataMatrix.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.Dimension; -import java.awt.Point; -import java.io.Serializable; - -/** - * Une matrice de données - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataMatrix { - - /** Logger */ - private static final Log log = LogFactory.getLog(DataMatrix.class); - - protected Object[][] data; - - protected int width; - - protected int height; - - protected int x; - - protected int y; - - public int getWidth() { - return width; - } - - public int getHeight() { - return height; - } - - public int getX() { - return x; - } - - public int getY() { - return y; - } - - public Object[][] getData() { - return data; - } - - public void setWidth(int width) { - this.width = width; - } - - public void setHeight(int height) { - this.height = height; - } - - public void setX(int x) { - this.x = x; - } - - public void setY(int y) { - this.y = y; - } - - public void createData() { - data = new Object[height][width]; - } - - public void setData(Object[][] data) { - this.data = data; - } - - public void copyData(DataMatrix incoming) { - - int x = incoming.getX(); - int y = incoming.getY(); - - Integer height = incoming.getHeight(); - Integer width = incoming.getWidth(); - - if (log.isDebugEnabled()) { - log.debug("copying incoming matrix (dim: " + - incoming.getDimension() + ", location: " + - incoming.getLocation() + ")"); - } - - for (int i = 0; i < width; i++) { - - for (int j = 0; j < height; j++) { - - Serializable value = incoming.getValue(i, j); - setValue(x + i, y + j, value); - } - } - } - - public Dimension getDimension() { - return new Dimension(width, height); - } - - public void setDimension(Dimension dim) { - height = (int) dim.getHeight(); - width = (int) dim.getWidth(); - } - - public Point getLocation() { - return new Point(x, y); - } - - public void setLocation(Point location) { - x = (int) location.getX(); - y = (int) location.getY(); - } - - public Serializable getValue(int x, int y) { - return data == null ? null : (Serializable) data[y][x]; - } - - public void setValue(int x, int y, Object data) { - - String cellData = data == null ? null : String.valueOf(data); - if (log.isDebugEnabled()) { - log.debug("Put data [" + x + "," + y + "] = " + cellData); - } - this.data[y][x] = cellData; - } - - public static Dimension getDimension(DataMatrix... datas) { - int width = 0; - int height = 0; - - for (DataMatrix request : datas) { - - int nWidth = request.getX() + request.getWidth(); - int nHeight = request.getY() + request.getHeight(); - if (nWidth > width) { - width = nWidth; - } - if (nHeight > height) { - height = nHeight; - } - } - return new Dimension(width, height); - } - - public static DataMatrix merge(DataMatrix... incomings) { - DataMatrix result = merge(-1, -1, incomings); - return result; - } - - public static DataMatrix merge(int rows, - int columns, - DataMatrix... incomings) { - Dimension dimension = getDimension(incomings); - - if (log.isDebugEnabled()) { - log.debug("Merge dimension : " + dimension); - } - - if (rows != -1) { - int height = (int) dimension.getHeight(); - // on verifie que récupère bien le bon count de lignes - if (rows != height) { - if (log.isWarnEnabled()) { - log.warn("No matching rows number : should have " + rows + - ", but was " + height); - } - } - } - - if (columns != -1) { - int width = (int) dimension.getWidth(); - // on verifie que récupère bien le bon count de colonnes - if (columns != width) { - if (log.isWarnEnabled()) { - log.warn("No matching columns number : should have " + - columns + ", but was " + width); - } - } - } - - DataMatrix result = new DataMatrix(); - result.setDimension(dimension); - result.createData(); - for (DataMatrix incoming : incomings) { - result.copyData(incoming); - } - return result; - } - - @Override - public String toString() { - ToStringBuilder builder = new ToStringBuilder(this); - builder.append("dimension", getDimension()); - builder.append("location", getLocation()); - return builder.toString(); - } - - public String getClipbordContent(boolean copyRowHeaders, - boolean copyColumnHeaders) { - - if (getWidth() <= 0 || getHeight() <= 0) { - return ""; - } - - StringBuilder buffer = new StringBuilder(); - - char sep = '\t'; - char eol = '\n'; - - for (int y = copyColumnHeaders ? 0 : 1, rows = getHeight(); y < rows; y++) { - - Serializable value; - - // nouvell ligne - - int x = copyRowHeaders ? 0 : 1; - - for (int columns = getWidth() - 1; x < columns; x++) { - - // sur chaque cellule (sauf la dernière) - value = getValue(x, y); - buffer.append(value).append(sep); - } - - // dernière cellule - value = getValue(x, y); - buffer.append(value); - - // fin de ligne - buffer.append(eol); - } - return buffer.toString(); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/Report.java b/observe-business/src/main/java/fr/ird/observe/report/model/Report.java deleted file mode 100644 index 318d22e..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/Report.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.Serializable; - -import static org.nuiton.i18n.I18n.t; - -public class Report implements Serializable { - - /** Logger. */ - private static final Log log = LogFactory.getLog(Report.class); - - /** l'id du report. */ - protected final String id; - - /** le libellé court du report. */ - protected final String name; - - /** la description du report. */ - protected final String description; - - /** les libellés des colonnes du report. */ - protected final String[] columnHeaders; - - /** les libellés des lignes du report. */ - protected final String[] rowHeaders; - - /** la liste des requêtes à jouer. */ - protected final ReportRequest[] requests; - - /** la liste des opérations à jouer. */ - protected final ReportOperation[] operations; - - /** la liste des variables du report. */ - protected final ReportVariable[] variables; - - /** la liste des variables de type repeat du report */ - protected final ReportVariable[] repeatVariables; - - private static final long serialVersionUID = 1L; - - public Report(String id, - String name, - String description, - String[] rowHeaders, - String[] columnHeaders, - ReportOperation[] operations, - ReportVariable[] variables, - ReportVariable[] repeatVariables, - ReportRequest... requests) { - this.id = id; - this.name = name; - this.description = description; - this.rowHeaders = rowHeaders; - this.columnHeaders = columnHeaders; - this.requests = requests; - this.operations = operations; - this.variables = variables; - this.repeatVariables = repeatVariables; - if (log.isDebugEnabled()) { - log.debug("New report [" + id + ":" + name + "], nb requests : " + - requests.length + ", nb objectOperations : " + - operations.length + ", nb variables : " + - variables.length + ", nb repeat variables : " + - repeatVariables.length); - } - } - - public String getId() { - return id; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - public int getRows() { - return rowHeaders == null ? -1 : rowHeaders.length; - } - - public int getColumns() { - return columnHeaders == null ? -1 : columnHeaders.length; - } - - public String[] getColumnHeaders() { - return columnHeaders; - } - - public String[] getRowHeaders() { - return rowHeaders; - } - - public ReportRequest[] getRequests() { - return requests; - } - - public ReportOperation[] getOperations() { - return operations; - } - - public ReportVariable[] getVariables() { - return variables; - } - - public ReportVariable[] getRepeatVariables() { - return repeatVariables; - } - - public boolean isVariableRequired() { - return variables.length > 0; - } - - @Override - public String toString() { - return t(name); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/ReportExecute.java b/observe-business/src/main/java/fr/ird/observe/report/model/ReportExecute.java deleted file mode 100644 index 8d15eec..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/ReportExecute.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.report.ReportBuilder; -import fr.ird.observe.report.model.operations.ExecuteRequests; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Objet contenant l'execution d'un report. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.7 - */ -public class ReportExecute { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReportExecute.class); - - /** le report a executer. */ - protected Report report; - - /** l'univers des valeurs possibles pour les variables que l'utilisateur doit sélectionner. */ - protected final Map<String, List<?>> variablesUniverse; - - /** l'univers des valeurs possibles pour les variables des requêtes en mode repeat. */ - protected final Map<String, List<?>> repeatVariablesUniverse; - - /** la source de données qui permet d'exécuter les requêtes hql. */ - protected DataSource source; - - public static final String TRIP_ID_VARIABLE = "tripId"; - - public ReportExecute() { - variablesUniverse = new TreeMap<String, List<?>>(); - repeatVariablesUniverse = new TreeMap<String, List<?>>(); - } - - public Report getReport() { - return report; - } - - public List<?> getVariableUniverse(String key) { - return variablesUniverse.get(key); - } - - public List<?> getRepeatVariableUniverse(String key) { - return repeatVariablesUniverse.get(key); - } - - public DataSource getSource() { - return source; - } - - public void setSource(DataSource source) { - this.source = source; - } - - public void populate(Report report, - String tripId) throws DataSourceException, TopiaException { - if (!checkDataSource(source)) { - - // source de donnee fermée - return; - } - this.report = report; - - // populate variables universe - doPopulateVariables(tripId); - } - - public DataMatrix execute(Map<String, Object> variables) throws DataSourceException, TopiaException { - - if (report == null) { - - // pas de report selectionne, donc pas de résultat - return null; - } - if (!checkDataSource(source)) { - - // source de donnee fermée - return null; - } - - if (!canExecute(variables)) { - - // la requete n'est pas exécutable - return null; - } - - // remplissage des variables de répétition si nécessaire - doPopulateRepeatVariables(variables); - - if (log.isDebugEnabled()) { - log.debug("Build result for report [" + report.getName() + - "] on " + variables.get(TRIP_ID_VARIABLE)); - } - - int rows = report.getRows(); - int columns = report.getColumns(); - - if (log.isDebugEnabled()) { - log.debug("Dimension : [" + rows + "," + columns + "]"); - } - - // execution des opérations sur le report - String txName = "execute"; - TopiaContext tx = source.beginTransaction(txName); - try { - - // creation de la première opération qui exécute les requètes - ExecuteRequests firstRequest = (ExecuteRequests) - ReportBuilder.newOperation(ExecuteRequests.OPERATION_NAME); - - // lancement de la première opération et la matrice de resultat - DataMatrix result = firstRequest.execute(tx, - report, - new DataMatrix(), - variables, - repeatVariablesUniverse - ); - - // lancement des opérations supplémentaires - for (ReportOperation objectOperation : report.getOperations()) { - - DataMatrix tmp = result; - if (log.isDebugEnabled()) { - log.debug("Apply objectOperation " + objectOperation + " to " + tmp); - } - result = objectOperation.execute(tx, - report, - tmp, - variables, - repeatVariablesUniverse - ); - } - if (log.isDebugEnabled()) { - log.debug("Final result : " + result); - } - return result; - } finally { - source.closeTransaction(tx, txName); - } - } - - public boolean canExecute(Map<String, Object> variables) { - - // il faut un report non null - if (report == null) { - - if (log.isInfoEnabled()) { - log.info("report is null"); - } - return false; - } - - for (ReportVariable request : report.getVariables()) { - - // on verifie qu'on a bien cette variable - String name = request.getName(); - if (!variables.containsKey(name)) { - - if (log.isInfoEnabled()) { - log.info("variable " + name + " is missing"); - } - return false; - } - - // et que sa valeur n'est pas null (ou vide) - Object variableValue = variables.get(name); - if (variableValue==null || StringUtils.isEmpty(variableValue.toString())) { - - if (log.isInfoEnabled()) { - log.info("variable " + name + " is empty or null"); - } - return false; - } - } - - // le report peut-être executé - return true; - } - - protected void doPopulateVariables(String tripId) throws DataSourceException, TopiaException { - - // on nettoye les univers de variables avant tout - variablesUniverse.clear(); - - if (report == null) { - - // pas de report, donc rien a faire - return; - } - - if (report.getVariables().length == 0) { - - // pas de variable utilise pour ce report - return; - } - - if (!checkDataSource(source)) { - - // source de donnee fermée - return; - } - String txName = "populateVariableUniverse"; - TopiaContext tx = source.beginTransaction(txName); - try { - - Map<String, Object> vars = new TreeMap<String, Object>(); - vars.put(TRIP_ID_VARIABLE, tripId); - for (ReportVariable variable : report.getVariables()) { - String hql = variable.getRequest(); - Object[] objects = ReportRequest.getParams(hql, vars); - List<?> universe = tx.findAll(hql, objects); - variablesUniverse.put(variable.getName(), universe); - } - } finally { - source.closeTransaction(tx, txName); - } - } - - protected void doPopulateRepeatVariables(Map<String, Object> variables) throws DataSourceException, TopiaException { - - // on nettoye les univers de variables de répétition avant tout - repeatVariablesUniverse.clear(); - - if (report.getRepeatVariables().length == 0) { - - // pas de variable de répétition - return; - } - if (!checkDataSource(source)) { - - // source de donnee fermée - return; - } - - String txName = "populateRepeatVariableUniverse"; - TopiaContext tx = source.beginTransaction(txName); - try { - for (ReportVariable variable : report.getRepeatVariables()) { - String hql = variable.getRequest(); - Object[] objects = ReportRequest.getParams(hql, variables); - List<?> universe = Lists.newArrayList(Sets.newLinkedHashSet(tx.findAll(hql, objects))); - repeatVariablesUniverse.put(variable.getName(), universe); - } - } finally { - source.closeTransaction(tx, txName); - } - } - - protected boolean checkDataSource(DataSource source) throws IllegalStateException { - if (source.wasClosed()) { - - // la source de donnée a été fermée - return false; - } - - if (!source.isOpen()) { - throw new IllegalStateException("data source is not opened."); - } - return true; - } -} - diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/ReportOperation.java b/observe-business/src/main/java/fr/ird/observe/report/model/ReportOperation.java deleted file mode 100644 index 284e01b..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/ReportOperation.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.awt.Dimension; -import java.awt.Point; -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -/** - * Pour caractériser une opération à lancer dans un report. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class ReportOperation implements Serializable { - - private static final long serialVersionUID = 1L; - - /** Logger */ - private static final Log log = LogFactory.getLog(ReportOperation.class); - - public abstract String getOperationName(); - - /** - * Calcule la position où positionner le rsultat dans la matrice sortante. - * - * @param model le report - * @param incoming la matrice entrante - * @return la position de la première cellule - */ - protected abstract Point computeLocation(Report model, - DataMatrix incoming); - - /** - * Calcule la dimension du résultat de l'opération. - * - * @param model le report - * @param incoming la matrice entrante - * @return la dimension des données de l'opération - */ - protected abstract Dimension computeDimension(Report model, - DataMatrix incoming); - - /** - * Pour executer l'opération. - * - * @param tx la transaction courante - * @param model le modèle - * @param incoming la matrice entrante - * @param variables le dictionnaire de variables utilisées dans le report - * @param repeatVariablesUniverse le dictionnaire des variables de répétition - * @return la matrice sortante - * @pour toute erreur de manipulation de base - */ - public abstract DataMatrix execute(TopiaContext tx, - Report model, - DataMatrix incoming, - Map<String, Object> variables, - Map<String, List<?>> repeatVariablesUniverse - ) throws TopiaException; - - protected ReportOperation() { - } - - protected DataMatrix createTmpMatrix(Report model, DataMatrix incoming) { - - DataMatrix result = new DataMatrix(); - - // calcul de la position des résultats de l'opération - Point location = computeLocation(model, incoming); - result.setLocation(location); - - // calcul de la taille des résultats de l'opération - Dimension dim = computeDimension(model, incoming); - result.setDimension(dim); - - // creation de la matrice - result.createData(); - - if (log.isDebugEnabled()) { - log.debug("Operation [" + getOperationName() + "] tmp matrix : " + result); - } - return result; - } - -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/ReportRequest.java b/observe-business/src/main/java/fr/ird/observe/report/model/ReportRequest.java deleted file mode 100644 index 056a424..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/ReportRequest.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model; - -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.awt.Dimension; -import java.awt.Point; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * Pour caractériser une requète à lancer dans un report. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ReportRequest implements Serializable { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReportRequest.class); - - /** le layout de la requete. */ - public enum RequestLayout { - /** lorsque les résultats de la requète sont les lignes du résultat. */ - row, - /** lorsque les résultats de la requète sont les colonnes du résultat. */ - column - } - - /** Un repeater optionnel sur la requête. */ - public static class RequestRepeat implements Serializable { - - protected final String variableName; - - protected final RequestLayout layout; - - private static final long serialVersionUID = 1L; - - public RequestRepeat(String variableName, RequestLayout layout) { - this.variableName = variableName; - this.layout = layout; - } - - public String getVariableName() { - return variableName; - } - - public RequestLayout getLayout() { - return layout; - } - - @Override - public String toString() { - ToStringBuilder builder = new ToStringBuilder(this); - builder.append("variableName", getVariableName()); - builder.append("layout", getLayout()); - return builder.toString(); - } - } - - /** layout de la requète. */ - protected final RequestLayout layout; - - /** la requète à exécuter. */ - protected final String request; - - /** la position de la requète. */ - protected final Point location; - - /** le repeater optionel. */ - protected final RequestRepeat repeat; - - public ReportRequest(RequestLayout layout, - int x, - int y, - String request, - RequestRepeat repeat) { - this.layout = layout; - this.request = request; - this.repeat = repeat; - location = new Point(x, y); - } - - public RequestLayout getLayout() { - return layout; - } - - public int getX() { - return (int) location.getX(); - } - - public int getY() { - return (int) location.getY(); - } - - public Point getLocation() { - return location; - } - - public String getRequest() { - return request; - } - - public RequestRepeat getRepeat() { - return repeat; - } - - public DataMatrix execute(TopiaContext tx, - Map<String, Object> params, - List<?> repeatValues) { - - DataMatrix result = new DataMatrix(); - for (Object repeatValue : repeatValues) { - params.put(repeat.getVariableName(), repeatValue); - DataMatrix tmp = execute(tx, params); - if (result == null) { - - // premiere requete executee - result = tmp; - result.setX(0); - result.setY(0); - } else { - switch (repeat.getLayout()) { - - case row: - - // on ajoute le resultat a droite de celui deja present - tmp.setX(result.getX() + result.getWidth()); - tmp.setY(result.getY()); - break; - - case column: - - // on ajoute le resultat en dessous de celui deja present - tmp.setX(result.getX()); - tmp.setY(result.getY() + result.getHeight()); - break; - } - result = DataMatrix.merge(result, tmp); - } - } - result.setX(getX()); - result.setY(getY()); - if (log.isDebugEnabled()) { - log.debug("Result location : " + result.getLocation()); - log.debug("Result data :\n" + result.getClipbordContent(true, true)); - } - return result; - } - - public DataMatrix execute(TopiaContext tx, - Map<String, Object> params) { - - // création des paramètres : couples (key, value) - Object[] datas = getParams(request, params); - if (log.isDebugEnabled()) { - log.debug("Request : " + request); - log.debug("Available params : " + params.keySet()); - log.debug("Params to use : " + Arrays.toString(datas)); - } - - // lancement de la requête - List<?> list = tx.findAll(request, datas); - if (log.isDebugEnabled()) { - log.debug("Result size : " + list.size()); - } - - // determination des dimensions du résultat - Dimension dimension = computeDimension(list); - if (log.isDebugEnabled()) { - log.debug("Result dimension : " + dimension); - } - - // construction du resultat - DataMatrix result = computeResult(dimension, list); - if (log.isDebugEnabled()) { - log.debug("Result location : " + result.getLocation()); - log.debug("Result data :\n" + result.getClipbordContent(true, true)); - } - return result; - } - - protected DataMatrix computeResult(Dimension dimension, List<?> list) { - - DataMatrix result = new DataMatrix(); - result.setDimension(dimension); - result.createData(); - - // le seul cas différent est le n-* (une ligne correspond à une colonne) - - int y = 0; - int x = 0; - - switch (layout) { - - case row: - - boolean uniqueColumn = result.getWidth() == 1; - - // les lignes du résultat sont les lignes du tableau - - for (Object row : list) { - - if (uniqueColumn) { - - // une seule colonne - result.setValue(0, y, row); - } else { - - x = 0; - Object[] cells = (Object[]) row; - for (Object cell : cells) { - result.setValue(x++, y, cell); - } - } - - // on passage a la ligne suivante - y++; - } - break; - case column: - - // les lignes du résultat sont les colonnes du tableau - - boolean uniqueRow = result.getHeight() == 1; - - for (Object col : list) { - - if (uniqueRow) { - - // une seule ligne - result.setValue(x, 0, col); - } else { - - y = 0; - Object[] cells = (Object[]) col; - for (Object cell : cells) { - result.setValue(x, y++, cell); - } - } - - // on passage a la colonne suivante - x++; - } - break; - } - - // on pousse la position du résultat - result.setX(getX()); - result.setY(getY()); - return result; - } - - protected Dimension computeDimension(List<?> list) { - - int height = 0; - int width = 0; - - switch (layout) { - - case row: - - // le count de result est le lastNamebre de lignes - height = list.size(); - - if (list.isEmpty()) { - - // vu qu'il n'y a pas de résultat, on ne peut rien dire - width = 0; - } else { - - Object o = list.get(0); - - if (o == null || !o.getClass().isArray()) { - - // une seule colonne - width = 1; - } else { - width = ((Object[]) o).length; - } - } - - break; - case column: - - // le count de result est le lastNamebre de colonnes - width = list.size(); - - if (list.isEmpty()) { - - // vu qu'il n'y a pas de résultat, on ne peut rien dire - height = 0; - } else { - - Object o = list.get(0); - - if (o == null || !o.getClass().isArray()) { - - // une seule ligne - height = 1; - } else { - height = ((Object[]) o).length; - } - } - - break; - } - return new Dimension(width, height); - } - - public static Object[] getParams(String request, Map<String, Object> params) { - - // on parcourt la liste de tous les paramètres pour savoir si on doit - // les inclure pour la requête donnée : - List<String> namesToUsed = new ArrayList<String>(); - for (String paramName : params.keySet()) { - if (request.contains(":" + paramName)) { - namesToUsed.add(paramName); - } - } - Object[] datas = new Object[namesToUsed.size() * 2]; - int index = 0; - for (String name : namesToUsed) { - Object value = params.get(name); - datas[index * 2] = name; - datas[index * 2 + 1] = value; - index++; - } - namesToUsed.clear(); - return datas; - } - - @Override - public String toString() { - ToStringBuilder builder = new ToStringBuilder(this); - builder.append("request", getRequest()); - builder.append("layout", getLayout()); - builder.append("location", getLocation()); - builder.append("repeatVariable", getRepeat()); - return builder.toString(); - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/ReportVariable.java b/observe-business/src/main/java/fr/ird/observe/report/model/ReportVariable.java deleted file mode 100644 index e789f67..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/ReportVariable.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model; - -import java.io.Serializable; - -/** - * La définition d'une variable utilisable dans un report. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.7 - */ -public class ReportVariable implements Serializable { - - private static final long serialVersionUID = 1L; - - protected String name; - - protected Class<?> type; - - protected String request; - - public ReportVariable(String name, Class<?> type, String request) { - this.name = name; - this.type = type; - this.request = request; - } - - public String getName() { - return name; - } - - public Class<?> getType() { - return type; - } - - public String getRequest() { - return request; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/operations/ExecuteRequests.java b/observe-business/src/main/java/fr/ird/observe/report/model/operations/ExecuteRequests.java deleted file mode 100644 index 4f59a6e..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/operations/ExecuteRequests.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model.operations; - -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportOperation; -import fr.ird.observe.report.model.ReportRequest; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.awt.Dimension; -import java.awt.Point; -import java.util.List; -import java.util.Map; - -/** - * Opération pour lancer les requètes d'un report. - * <p/> - * Cette opération est toujours exécuter en premier lors de la construction - * du résultat d'un report. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ExecuteRequests extends ReportOperation { - - /** Logger */ - private static final Log log = LogFactory.getLog(ExecuteRequests.class); - - private static final long serialVersionUID = 1L; - - public static final String OPERATION_NAME = "ExecuteRequests"; - - public ExecuteRequests() { - } - - public String getOperationName() { - return OPERATION_NAME; - } - - @Override - public DataMatrix execute(TopiaContext tx, - Report report, - DataMatrix incoming, - Map<String, Object> variables, - Map<String, List<?>> repeatVariablesUniverse) { - - if (log.isDebugEnabled()) { - log.debug("Launch " + this); - } - - ReportRequest[] requests = report.getRequests(); - - DataMatrix[] requestResults = new DataMatrix[requests.length]; - - int i = 0; - for (ReportRequest request : requests) { - - ReportRequest.RequestRepeat repeatVariable = request.getRepeat(); - - DataMatrix result; - - if (repeatVariable == null) { - - // requete simple sans repetition - result = request.execute(tx, variables); - } else { - - // on a une requete avec repetition - String repeatVariableName = repeatVariable.getVariableName(); - List<?> repeatValues = repeatVariablesUniverse.get(repeatVariableName); - - try { - result = request.execute(tx, - variables, - repeatValues - ); - } finally { - //FIXME rendre etanche l'utilisation des variables - // la variable a ete ajoutee pendant l'execution - // il faut la retirer - variables.remove(repeatVariable.getVariableName()); - } - - } - - requestResults[i++] = result; - } - - int rows = report.getRows(); - int columns = report.getColumns(); - - DataMatrix result = DataMatrix.merge(rows, columns, requestResults); - return result; - } - - @Override - protected Point computeLocation(Report model, DataMatrix incoming) { - Point result = new Point(0, 0); - return result; - } - - @Override - protected Dimension computeDimension(Report model, DataMatrix incoming) { - - Dimension result = new Dimension(0, 0); - return result; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/operations/GroupByLength.java b/observe-business/src/main/java/fr/ird/observe/report/model/operations/GroupByLength.java deleted file mode 100644 index bf27e69..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/operations/GroupByLength.java +++ /dev/null @@ -1,109 +0,0 @@ -package fr.ird.observe.report.model.operations; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportOperation; -import org.apache.commons.lang3.mutable.MutableInt; -import org.nuiton.topia.TopiaContext; - - -import java.awt.Dimension; -import java.awt.Point; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * To group by legnth (first column, second row is count). - * - * I don't know how to make this with hibernate the group by + sum does not work :(. - * - * Created on 5/23/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class GroupByLength extends ReportOperation { - - private static final long serialVersionUID = 1L; - - private static final String OPERATION_NAME = "GroupByLength"; - - @Override - public String getOperationName() { - return OPERATION_NAME; - } - - @Override - protected Point computeLocation(Report model, DataMatrix incoming) { - Point result = new Point(0, incoming.getHeight()); - return result; - } - - @Override - protected Dimension computeDimension(Report model, DataMatrix incoming) { - Set<String> lengths = new HashSet<String>(); - for (int i = 0; i < incoming.getHeight(); i++) { - lengths.add((String) incoming.getValue(0, i)); - } - Dimension result = new Dimension(incoming.getWidth(), lengths.size()); - return result; - } - - @Override - public DataMatrix execute(TopiaContext tx, Report model, DataMatrix incoming, Map<String, Object> variables, Map<String, List<?>> repeatVariablesUniverse) { - - // Première passe pour grouper par classe de taille - Map<String, MutableInt> data = new LinkedHashMap<String, MutableInt>(); - for (int i = 0, nbRows = incoming.getHeight(); i < nbRows; i++) { - - String length = (String) incoming.getValue(0, i); - Integer count = Integer.valueOf(incoming.getValue(1, i).toString()); - - MutableInt mutableInt = data.get(length); - if (mutableInt == null) { - mutableInt = new MutableInt(); - data.put(length, mutableInt); - } - mutableInt.add(count); - - } - - // Deuxième passe pour remplir la matrice - DataMatrix result = createTmpMatrix(model, incoming); - int row = 0; - for (Map.Entry<String, MutableInt> entry : data.entrySet()) { - String length = entry.getKey(); - MutableInt mutableInt = entry.getValue(); - result.setValue(0, row, length); - result.setValue(1, row, mutableInt.intValue()); - row++; - } - - return result; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumColumn.java b/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumColumn.java deleted file mode 100644 index eeea099..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumColumn.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model.operations; - -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportOperation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.awt.Dimension; -import java.awt.Point; -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -/** - * Opération pour calculer la somme de toutes les cellules d'une colonne. - * <p/> - * Le résultat de l'opération vient se placer dans une nouvelle ligne en bas - * du tableau. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SumColumn extends ReportOperation { - - /** Logger */ - private static final Log log = - LogFactory.getLog(SumColumn.class); - - private static final long serialVersionUID = 1L; - - private static final String OPERATION_NAME = "SumColumn"; - - - public SumColumn() { - } - - public String getOperationName() { - return OPERATION_NAME; - } - - @Override - public DataMatrix execute(TopiaContext tx, - Report model, - DataMatrix incoming, - Map<String, Object> variables, - Map<String, List<?>> repeatVariablesUniverse) { - - if (log.isDebugEnabled()) { - log.debug("Launch " + this); - } - - // construction du resultat - - DataMatrix tmpMatrix = createTmpMatrix(model, incoming); - - for (int i = 0, nbColumns = incoming.getWidth(); i < nbColumns; i++) { - - Object result = getColumnData(i, incoming); - tmpMatrix.setValue(i, 0, result); - if (log.isDebugEnabled()) { - log.debug("objectOperation [" + i + ",0] = " + result); - } - } - - DataMatrix result = DataMatrix.merge(incoming, tmpMatrix); - return result; - } - - protected Object getColumnData(int column, DataMatrix incoming) { - Double result = 0d; - - int nbRows = incoming.getHeight(); - - for (int row = 0; row < nbRows; row++) { - Serializable o = incoming.getValue(column, row); - - if (o == null || "null".equals(o)) { - o = 0; - } - Double d; - try { - d = Double.valueOf(o.toString()); - } catch (NumberFormatException e) { - // une des données de la colonne n'est pas un count - // on sort directement - if (log.isDebugEnabled()) { - log.debug("Could not convert " + o + " to number", e); - } - return "-"; - } - result += d; - } - - return result; - } - - @Override - protected Point computeLocation(Report model, DataMatrix incoming) { - Point result = new Point(0, incoming.getHeight()); - return result; - } - - @Override - protected Dimension computeDimension(Report model, DataMatrix incoming) { - Dimension result = new Dimension(incoming.getWidth(), 1); - return result; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumIntColumn.java b/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumIntColumn.java deleted file mode 100644 index a0e79ec..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumIntColumn.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model.operations; - -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportOperation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.awt.Dimension; -import java.awt.Point; -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -/** - * Opération pour calculer la somme entière de toutes les cellules d'une colonne. - * <p/> - * Le résultat de l'opération vient se placer dans une nouvelle ligne en bas - * du tableau. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SumIntColumn extends ReportOperation { - - /** Logger */ - private static final Log log = - LogFactory.getLog(SumIntColumn.class); - - private static final long serialVersionUID = 1L; - - private static final String OPERATION_NAME = "SumIntColumn"; - - - public SumIntColumn() { - } - - public String getOperationName() { - return OPERATION_NAME; - } - - @Override - public DataMatrix execute(TopiaContext tx, - Report model, - DataMatrix incoming, - Map<String, Object> variables, - Map<String, List<?>> repeatVariablesUniverse) { - - if (log.isDebugEnabled()) { - log.debug("Launch " + this); - } - - // construction du resultat - - DataMatrix tmpMatrix = createTmpMatrix(model, incoming); - - for (int i = 0, nbColumns = incoming.getWidth(); i < nbColumns; i++) { - - Object result = getColumnData(i, incoming); - tmpMatrix.setValue(i, 0, result); - if (log.isDebugEnabled()) { - log.debug("objectOperation [" + i + ",0] = " + result); - } - } - - DataMatrix result = DataMatrix.merge(incoming, tmpMatrix); - return result; - } - - protected Object getColumnData(int column, DataMatrix incoming) { - Double result = 0d; - - int nbRows = incoming.getHeight(); - - for (int row = 0; row < nbRows; row++) { - Serializable o = incoming.getValue(column, row); - - if (o == null || "null".equals(o)) { - o = 0; - } - Double d; - try { - d = Double.valueOf(o.toString()); - } catch (NumberFormatException e) { - // une des données de la colonne n'est pas un count - // on sort directement - if (log.isDebugEnabled()) { - log.debug("Could not convert " + o + " to number", e); - } - return "-"; - } - result += d; - } - - return result.intValue(); - } - - @Override - protected Point computeLocation(Report model, DataMatrix incoming) { - Point result = new Point(0, incoming.getHeight()); - return result; - } - - @Override - protected Dimension computeDimension(Report model, DataMatrix incoming) { - Dimension result = new Dimension(incoming.getWidth(), 1); - return result; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumIntRow.java b/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumIntRow.java deleted file mode 100644 index 243aec2..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumIntRow.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model.operations; - -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportOperation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.awt.Dimension; -import java.awt.Point; -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -/** - * Opération pour calculer la somme entière de toutes les cellules d'une ligne. - * <p/> - * Le résultat de l'opération vient se placer dans une nouvelle colonne à - * droite du tableau. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SumIntRow extends ReportOperation { - - /** Logger */ - private static final Log log = LogFactory.getLog(SumIntRow.class); - - public static final String OPERATION_NAME = "SumIntRow"; - - private static final long serialVersionUID = 1L; - - public SumIntRow() { - } - - public String getOperationName() { - return OPERATION_NAME; - } - - @Override - public DataMatrix execute(TopiaContext tx, - Report model, - DataMatrix incoming, - Map<String, Object> variables, - Map<String, List<?>> repeatVariablesUniverse) { - if (log.isDebugEnabled()) { - log.debug("Launch " + this); - } - - // construction du result - - DataMatrix tmpMatrix = createTmpMatrix(model, incoming); - - for (int i = 0, nbRows = incoming.getHeight(); i < nbRows; i++) { - - Object result = getRowData(i, incoming); - tmpMatrix.setValue(0, i, result); - if (log.isDebugEnabled()) { - log.debug("objectOperation [0, " + i + "] = " + result); - } - } - - DataMatrix result = DataMatrix.merge(incoming, tmpMatrix); - return result; - } - - - protected Object getRowData(int row, DataMatrix incoming) { - - Double result = 0d; - - int nbColumns = incoming.getWidth(); - - for (int col = 0; col < nbColumns; col++) { - Serializable o = incoming.getValue(col, row); - - if (o == null || "null".equals(o)) { - o = 0; - } - Double d; - try { - d = Double.valueOf(o.toString()); - } catch (NumberFormatException e) { - // une des données de la colonne n'est pas un count - // on sort directement - if (log.isDebugEnabled()) { - log.debug("Could not convert " + o + " to number", e); - } - return "-"; - } - result += d; - } - - return result.intValue(); - } - - @Override - protected Point computeLocation(Report model, DataMatrix incoming) { - Point result = new Point(incoming.getWidth(), 0); - return result; - } - - @Override - protected Dimension computeDimension(Report model, DataMatrix incoming) { - - Dimension result = new Dimension(1, incoming.getHeight()); - return result; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumRow.java b/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumRow.java deleted file mode 100644 index 6480afc..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/model/operations/SumRow.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.report.model.operations; - -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportOperation; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - - -import java.awt.Dimension; -import java.awt.Point; -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -/** - * Opération pour calculer la somme de toutes les cellules d'une ligne. - * <p/> - * Le résultat de l'opération vient se placer dans une nouvelle colonne à - * droite du tableau. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SumRow extends ReportOperation { - - /** Logger */ - private static final Log log = LogFactory.getLog(SumRow.class); - - public static final String OPERATION_NAME = "SumRow"; - - private static final long serialVersionUID = 1L; - - public SumRow() { - } - - public String getOperationName() { - return OPERATION_NAME; - } - - @Override - public DataMatrix execute(TopiaContext tx, - Report model, - DataMatrix incoming, - Map<String, Object> variables, - Map<String, List<?>> repeatVariablesUniverse) { - if (log.isDebugEnabled()) { - log.debug("Launch " + this); - } - - // construction du result - - DataMatrix tmpMatrix = createTmpMatrix(model, incoming); - - for (int i = 0, nbRows = incoming.getHeight(); i < nbRows; i++) { - - Object result = getRowData(i, incoming); - tmpMatrix.setValue(0, i, result); - if (log.isDebugEnabled()) { - log.debug("objectOperation [0, " + i + "] = " + result); - } - } - - DataMatrix result = DataMatrix.merge(incoming, tmpMatrix); - return result; - } - - - protected Object getRowData(int row, DataMatrix incoming) { - - Double result = 0d; - - int nbColumns = incoming.getWidth(); - - for (int col = 0; col < nbColumns; col++) { - Serializable o = incoming.getValue(col, row); - - if (o == null || "null".equals(o)) { - o = 0; - } - Double d; - try { - d = Double.valueOf(o.toString()); - } catch (NumberFormatException e) { - // une des données de la colonne n'est pas un count - // on sort directement - if (log.isDebugEnabled()) { - log.debug("Could not convert " + o + " to number", e); - } - return "-"; - } - result += d; - } - - return result; - } - - @Override - protected Point computeLocation(Report model, DataMatrix incoming) { - Point result = new Point(incoming.getWidth(), 0); - return result; - } - - @Override - protected Dimension computeDimension(Report model, DataMatrix incoming) { - - Dimension result = new Dimension(1, incoming.getHeight()); - return result; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/report/package-info.java b/observe-business/src/main/java/fr/ird/observe/report/package-info.java deleted file mode 100644 index 48999b3..0000000 --- a/observe-business/src/main/java/fr/ird/observe/report/package-info.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -/** - * Ce paquetage définit l'api des reports d'observe : - * {@link Report}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.7 - */ -package fr.ird.observe.report; - diff --git a/observe-business/src/main/java/fr/ird/observe/test/TestHelper.java b/observe-business/src/main/java/fr/ird/observe/test/TestHelper.java deleted file mode 100644 index f5345ea..0000000 --- a/observe-business/src/main/java/fr/ird/observe/test/TestHelper.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.test; - -import fr.ird.observe.ObserveApplicationContext; -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.db.util.SecurityModel; -import jaxx.runtime.context.DefaultApplicationContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.config.ApplicationConfig; -import org.nuiton.i18n.I18n; - -import java.io.File; -import java.util.Date; -import java.util.Locale; - -/** - * @author Tony Chemit - chemit@codelutin.com - */ -public abstract class TestHelper { - - /** Logger */ - private static final Log log = LogFactory.getLog(TestHelper.class); - - static private final String TEST_BASEDIR_PATTERN = "target%1$ssurefire-workdir%1$s%2$td_%2$tm_%2$tY%1$s%2$tH_%2$tM_%2$tS"; - - public static final String TEST_H2_LOGIN = "sa"; - - public static final char[] TEST_H2_PASSWORD = "sa".toCharArray(); - - public static final String TEST_REMOTE_URL = "jdbc:postgresql://localhost/obstuna-test"; -// public static final String TEST_REMOTE_URL = "jdbc:postgresql://demo.codelutin.com/obstuna"; - - public static final String TEST_REMOTE_ADMIN_LOGIN = "admin"; - - public static final String TEST_REMOTE_UTILISATEUR_LOGIN = "utilisateur"; - - public static final String TEST_REMOTE_REFERENTIEL_LOGIN = "referentiel"; - - public static final String[] TEST_REMOTE_TECHNICIENS_LOGIN = {"technicien1", "technicien2", "technicien3"}; - - public static final char[] TEST_REMOTE_PASSWORD = "a".toCharArray(); - - static private Long testsTimeStamp; - - static private File testsBasedir; - - static private File basedir; - - public static File TEST_BASEDIR; - - protected static boolean initI18n; - - public static Long getTestsTimeStamp() { - if (testsTimeStamp == null) { - testsTimeStamp = System.currentTimeMillis(); - if (log.isInfoEnabled()) { - log.info("tests timestamp : " + testsTimeStamp); - } - } - return testsTimeStamp; - } - - public static File getTestDir(Class<?> testClass) { - if (testsBasedir == null) { - String tmp = System.getProperty("basedir"); - if (tmp == null) { - tmp = new File("").getAbsolutePath(); - } - basedir = new File(tmp); - String name = String.format(TEST_BASEDIR_PATTERN, - File.separator, - new Date(getTestsTimeStamp()) - ); - testsBasedir = new File(new File(tmp), name); - if (log.isInfoEnabled()) { - log.info("tests basedir : " + testsBasedir); - } - } - return new File(testsBasedir, testClass.getSimpleName()); - } - - public static File newLocalDB(String name) { - return new File(TEST_BASEDIR, "localDB_" + name); - } - - public static File getBasedir() { - return basedir; - } - - public static void setConfig(String key, String value) { - DefaultApplicationContext context = - ObserveServiceHelper.get(); - ApplicationConfig config = - context.getContextValue(ApplicationConfig.class); - config.setOption(key, value); - } - - public static void createApplicationContext() { - - ObserveServiceHelper.close(); - ObserveApplicationContext context = new ObserveApplicationContext(); - ApplicationConfig conf = new ApplicationConfig(); - context.setContextValue(conf); - ObserveServiceHelper.set(context); - } - - public static void initTest(Class<?> testClass) { - - if (!initI18n) { - I18n.setDefaultLocale(Locale.FRENCH); - initI18n = true; - } - - TEST_BASEDIR = getTestDir(testClass); - } - - public static SecurityModel createTestSecurityModel() { - - SecurityModel securityModel = new SecurityModel(); - - securityModel.setAdministrateur(TEST_REMOTE_ADMIN_LOGIN); -// securityModel.setRole(Arrays.asList(TEST_REMOTE_TECHNICIENS_LOGIN), SecurityModel.Role.technicien); - securityModel.setRole(TEST_REMOTE_UTILISATEUR_LOGIN, SecurityModel.Role.utilisateur, false); - securityModel.setRole(TEST_REMOTE_REFERENTIEL_LOGIN, SecurityModel.Role.referentiel, false); - return securityModel; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/util/Scripts.java b/observe-business/src/main/java/fr/ird/observe/util/Scripts.java deleted file mode 100644 index 385e309..0000000 --- a/observe-business/src/main/java/fr/ird/observe/util/Scripts.java +++ /dev/null @@ -1,168 +0,0 @@ -package fr.ird.observe.util; - -/* - * #%L - * ObServe :: Entities - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.version.Version; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -/** - * Created on 8/25/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class Scripts { - - /** Logger. */ - private static final Log log = LogFactory.getLog(Scripts.class); - - public static final String OBSTUNA_SCRIPT_PATTERN = "/db/%1$s/obstuna%2$s.sql"; - - public static final String BACKUP_SCRIPT_PATTERN = "/db/%1$s/%2$s.sql.gz"; - - public static final String REFERENTIEL_SCRIPT = "referentiel"; - - public static final String FULL_SCRIPT = "referentiel-data"; - - public static void loadScript(Connection connection, - String script) throws SQLException { - - - if (log.isDebugEnabled()) { - log.debug("will execute a script..."); - } - PreparedStatement sta = - connection.prepareStatement(script); - try { - sta.executeUpdate(); - - } finally { - - sta.close(); - } - } - - public static int loadScriptContent(String scriptName, - StringBuilder out) throws IOException { - - InputStream stream = Scripts.class.getResourceAsStream(scriptName); - return loadScriptContent(stream, out); - } - - public static int loadScriptContent(URL scriptName, - StringBuilder out) throws IOException { - - InputStream stream = scriptName.openStream(); - return loadScriptContent(stream, out); - } - - public static int loadScriptContent(InputStream stream, - StringBuilder out) throws IOException { - - BufferedReader buffer = new BufferedReader( - new InputStreamReader(stream)); - try { - - String line; - int nbLines = 0; - - while ((line = buffer.readLine()) != null) { - String trimLine = line.trim(); - if (trimLine.isEmpty() || - trimLine.startsWith("--") || - line.contains("client_encoding")) { - continue; - } - out.append(line).append('\n'); - nbLines++; - } - - return nbLines; - - } finally { - buffer.close(); - } - } - -// public static void loadScript(DataSource service, -// final String script) throws DataSourceException { -// -// TopiaContext tx = -// service.beginTransaction("loadScript"); -// -// try { -// -// ((TopiaContextImplementor) tx).getHibernate().doWork(new Work() { -// -// @Override -// public void execute(Connection connection) throws SQLException { -// loadScript(connection, script); -// } -// }); -// service.commitTransaction(tx, "loadScript"); -// -// } catch (DataSourceException e) { -// throw e; -// } catch (Exception e) { -// service.rollbackTransaction(tx, "loadScript"); -// } finally { -// service.closeTransaction(tx, "loadScript"); -// } -// } - - public static URL getBackupScriptURL(Version version, String pattern) { - String path = getBackupScript(version, pattern); - if (log.isInfoEnabled()) { - log.info("script = " + path); - } - URL result = Scripts.class.getResource(path); - return result; - } - - public static String getBackupScript(Version version, String loadScript) { - String result = String.format( - BACKUP_SCRIPT_PATTERN, - version.toString(), - loadScript - ); - if (log.isInfoEnabled()) { - log.info(result); - } - return result; - } - - public static URL getLastReferentielBackup() { - URL url = getBackupScriptURL(DBTestHelper.V_LAST, REFERENTIEL_SCRIPT); - return url; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/validation/ObserveValidator.java b/observe-business/src/main/java/fr/ird/observe/validation/ObserveValidator.java deleted file mode 100644 index b684753..0000000 --- a/observe-business/src/main/java/fr/ird/observe/validation/ObserveValidator.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.validation; - -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.util.ValueStack; -import fr.ird.observe.ObserveApplicationContext; -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.db.DataSourceFactory; -import jaxx.runtime.validator.swing.SwingValidator; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorFactory; -import org.nuiton.validator.NuitonValidatorProvider; -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.xwork2.XWork2ValidatorUtil; - -/** - * Une surcharge du validateur swing offert par jaxx pour pouvoir ajouter dans - * la stack le DataContext (pour faire de la validation sur le context de - * données d'un niveau supérieur (valider une marée à partir d'une route par - * exemple). - * - * @param <B> le type d'objet a valider - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ObserveValidator<B> extends SwingValidator<B> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveValidator.class); - - /** un etat pour initialiser la stack une unique fois la stack */ - private static boolean init; - - private static ValidationContext validationContext; - - public static <B> ObserveValidator<B> newValidator(Class<B> type, - String context, - NuitonValidatorScope... scopes) { - return new ObserveValidator<B>( - type, - context, - scopes - ); - } - - public static <B> ObserveValidator<B> newValidator(NuitonValidatorProvider provider, - Class<B> type, - String context, - NuitonValidatorScope... scopes) { - return new ObserveValidator<B>( - provider, - type, - context, - scopes - ); - } - - public ObserveValidator( - Class<B> type, - String context, - NuitonValidatorScope... scopes) { - super(NuitonValidatorFactory.getDefaultProvider(), type, context, scopes); - } - - public ObserveValidator(NuitonValidatorProvider provider, - Class<B> type, - String context, - NuitonValidatorScope... scopes) { - super(provider, type, context, scopes); - } - - @Override - protected void rebuildDelegateValidator(Class<B> beanType, - String context, - NuitonValidatorScope... scopes) { - super.rebuildDelegateValidator(beanType, context, scopes); - - if (isInit()) { - // deja initialise - return; - } - - // on positionne dans la stack de dataContext pour pouvoir faire de la - // validation sur des objets dans le scope. - - ValidationContext dataContext = getValidationContext(); - if (dataContext == null) { - - // aucun context de validation enregistré - if (log.isDebugEnabled()) { - log.debug("No validation context registred, try in application context..."); - } - ObserveApplicationContext rootContext; - rootContext = ObserveServiceHelper.get(); - if (rootContext == null) { - throw new IllegalStateException( - "pas de context d'application enregistré... utiliser la " + - "methode " + - DataSourceFactory.class.getName() + - "#setApplicationContext(context)"); - } - dataContext = rootContext.getValidationContext(); - } - - reloadDataContext(dataContext, true); - - // on brand pour ne jamais revenir ici - setInit(true); - } - - public static void reloadDataContext(ValidationContext dataContext, - boolean strict) { - if (dataContext != validationContext) { - - // keep this validation context - setValidationContext(dataContext); - } - ValueStack valueStack; - ActionContext context = ActionContext.getContext(); - if (context == null) { - - if (strict) { - throw new IllegalStateException( - "pas de context xworks enregistré... utiliser la methode " + - ActionContext.class.getName() + "#setContext(context)"); - } - - valueStack = XWork2ValidatorUtil.getSharedValueStack(); - if (valueStack == null) { - return; - } - } else { - valueStack = context.getValueStack(); - } - - if (log.isDebugEnabled()) { - log.debug("Enregistrement du context de validation [" + dataContext + "] dans la valueStack de " + - "validation (" + valueStack + ')'); - } - - valueStack.push(dataContext); - } - - public static ValidationContext getValidationContext() { - return validationContext; - } - - public static void setValidationContext(ValidationContext validationContext) { - ObserveValidator.validationContext = validationContext; - // a chaque fois qu'on change le contexte de validation - // il faudra reinitiliser la stack - setInit(false); - } - - private static boolean isInit() { - return init; - } - - private static void setInit(boolean init) { - ObserveValidator.init = init; - } - - -} diff --git a/observe-business/src/main/java/fr/ird/observe/validation/ValidationContext.java b/observe-business/src/main/java/fr/ird/observe/validation/ValidationContext.java deleted file mode 100644 index 9fe68dc..0000000 --- a/observe-business/src/main/java/fr/ird/observe/validation/ValidationContext.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.validation; - -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.entities.Activity; -import fr.ird.observe.entities.Set; -import fr.ird.observe.entities.Trip; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.SetLongline; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TripSeine; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; - -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Contient les objets en cours de validation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ValidationContext { - - /** Logger */ - static private final Log log = LogFactory.getLog(ValidationContext.class); - - public static final String VALIDATION_TRANSACTION_NAME = "validation"; - - protected DataSource dataSource; - - protected TopiaContext tx; - - protected DataContext dataContext; - - protected Map<String, Object> cache; - - private List<?> referentielList; - - public Map<String, Object> getCache() { - if (cache == null) { - cache = new TreeMap<String, Object>(); - } - return cache; - } - - public void cleanCache() { - getCache().clear(); - referentielList = null; - cleanTransaction(); - } - - public DataSource getDataSource() { - return dataSource; - } - - public void close() { - closeDataSource(); - dataContext = null; - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - close(); - } - - public void closeDataSource() { - closeTransaction(); - dataSource = null; - } - - protected void closeTransaction() { - if (tx != null) { - if (log.isDebugEnabled()) { - log.debug("close 'validation' transaction"); - } - try { - dataSource.closeTransaction(tx, VALIDATION_TRANSACTION_NAME); - } catch (DataSourceException e) { - if (log.isErrorEnabled()) { - log.error("Could not close transaction", e); - } - } finally { - tx = null; - } - } - } - - protected void cleanTransaction() { - if (tx != null) { - if (log.isDebugEnabled()) { - log.debug("clean 'validation' transaction"); - } - try { - dataSource.rollbackTransaction(tx, VALIDATION_TRANSACTION_NAME); - } catch (DataSourceException e) { - if (log.isErrorEnabled()) { - log.error("Could not clean transaction", e); - } - } - } - } - - public DataContext getDataContext() { - return dataContext; - } - - public void setDataSource(DataSource dataSource) { - if (this.dataSource != null) { - closeDataSource(); - } - if (log.isDebugEnabled()) { - log.debug("Attach data source " + (dataSource == null ? "null" : dataSource.getShortLabel())); - } - this.dataSource = dataSource; - } - - public void setDataContext(DataContext dataContext) { - if (log.isInfoEnabled()) { - log.info("Attach data context " + dataContext); - } - this.dataContext = dataContext; - ObserveValidator.reloadDataContext(this, false); - } - - public Trip getCurrentTrip() { - - Trip result = null; - - String selectedTripId = dataContext.getSelectedTripId(); - if (selectedTripId != null) { - if (selectedTripId.contains("Seine")) { - result = getCurrentTripSeine(); - } else { - result = getCurrentTripLongline(); - } - } - return result; - - } - - public TripSeine getCurrentTripSeine() { - TripSeine result = getEntity(TripSeine.class, dataContext.getSelectedTripId()); - return result; - } - - public TripLongline getCurrentTripLongline() { - TripLongline result = getEntity(TripLongline.class, dataContext.getSelectedTripId()); - return result; - } - - public Route getCurrentRoute() { - Route result = getEntity(Route.class, dataContext.getSelectedRouteId()); - return result; - } - - public Activity getCurrentActivity() { - - Activity result = null; - - String selectedActivityId = dataContext.getSelectedActivityId(); - if (selectedActivityId != null) { - if (selectedActivityId.contains("Seine")) { - result = getCurrentActivitySeine(); - } else { - result = getCurrentActivityLongline(); - } - } - return result; - - } - - public ActivitySeine getCurrentActivitySeine() { - ActivitySeine result = getEntity(ActivitySeine.class, dataContext.getSelectedActivityId()); - return result; - } - - public ActivityLongline getCurrentActivityLongline() { - ActivityLongline result = getEntity(ActivityLongline.class, dataContext.getSelectedActivityId()); - return result; - } - - public Set getCurrentSet() { - - Set result = null; - - String selectedSetId = dataContext.getSelectedSetId(); - if (selectedSetId != null) { - if (selectedSetId.contains("Seine")) { - result = getCurrentSetSeine(); - } else { - result = getCurrentSetLongline(); - } - } - return result; - - } - - public SetSeine getCurrentSetSeine() { - SetSeine result = getEntity(SetSeine.class, dataContext.getSelectedSetId()); - return result; - } - - public SetLongline getCurrentSetLongline() { - SetLongline result = getEntity(SetLongline.class, dataContext.getSelectedSetId()); - return result; - } - - public FloatingObject getCurrentFloatingObject() { - FloatingObject result = getEntity(FloatingObject.class, dataContext.getSelectedFloatingObjectId()); - return result; - } - - public List<?> getEditingReferentielList() { - return referentielList; - } - - public void setEditingReferentielList(List<?> referentielList) { - if (log.isDebugEnabled()) { - log.debug("Add referentielList (size : " + (referentielList == null ? 0 : referentielList.size()) + ")"); - } - this.referentielList = referentielList; - } - - public TopiaContext getTx() throws DataSourceException { - if (tx == null) { - if (dataSource != null) { - if (log.isInfoEnabled()) { - log.info("Open a new transaction " + tx); - } - tx = dataSource.beginTransaction(VALIDATION_TRANSACTION_NAME); - } - } - return tx; - } - - public <E extends TopiaEntity> E getEntity(Class<E> klass, String id) { - - if (dataSource == null || dataContext == null || !dataSource.isOpen() || id == null) { - return null; - } - Object o = getCache().get(id); - if (o != null) { - if (log.isDebugEnabled()) { - log.debug("Use cached entity : " + id); - } - // found in cache - return (E) o; - } - try { - TopiaContext tx = getTx(); - if (tx == null) { - return null; - } - TopiaDAO<E> dao = dataSource.getDAO(tx, klass); - E result = dao.findByTopiaId(id); - if (log.isInfoEnabled()) { - log.info("Put entity into cache : " + id); - } - getCache().put(id, result); - return result; - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("Could not obtain " + id, e); - } - return null; - } - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/validation/ValidationMessageDetector.java b/observe-business/src/main/java/fr/ird/observe/validation/ValidationMessageDetector.java deleted file mode 100644 index 7815a45..0000000 --- a/observe-business/src/main/java/fr/ird/observe/validation/ValidationMessageDetector.java +++ /dev/null @@ -1,559 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.validation; - -import fr.ird.observe.ObserveDAOHelper; -import fr.ird.observe.ObserveEntityEnum; -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.seine.TripSeine; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.nuiton.topia.persistence.EntityVisitor; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.TopiaEntityRef; -import org.nuiton.validator.bean.simple.SimpleBeanValidator; -import org.nuiton.validator.bean.simple.SimpleBeanValidatorEvent; -import org.nuiton.validator.bean.simple.SimpleBeanValidatorListener; -import org.nuiton.validator.bean.simple.SimpleBeanValidatorMessage; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Deque; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; - -/** - * Le detecteur de messages de validation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class ValidationMessageDetector implements EntityVisitor, - SimpleBeanValidatorListener { - - /** Logger */ - private static final Log log = - LogFactory.getLog(ValidationMessageDetector.class); - - public static final String SEPARATOR = "/"; - - /** le path courant depuis le depart */ - protected Deque<TopiaEntity> path; - - /** le dictionnaire des paths d'entites detectees */ - protected SortedMap<TopiaEntityRef, List<SimpleBeanValidatorMessage<?>>> refs; - - protected StringBuilder accessorExpression; - - protected TopiaEntity root; - - protected TopiaEntityRef currentRef; - - protected Set<TopiaEntity> explored; - - /** le dictionnaire des validateurs utilisables */ - protected final ValidatorsMap validators; - - protected ValidationContext context; - - public ValidationContext getContext() { - if (context == null) { - context = ObserveServiceHelper.getValidationContext(); - } - return context; - } - - public ValidationMessageDetector(ValidatorsMap validators) { - this.validators = validators; - path = new LinkedList<TopiaEntity>(); - explored = new HashSet<TopiaEntity>(); - refs = new TreeMap<TopiaEntityRef, List<SimpleBeanValidatorMessage<?>>>(); - accessorExpression = new StringBuilder(); - for (SimpleBeanValidator<?> v : validators.values()) { - v.setBean(null); - } - } - - public void detectMessages(TopiaEntity... entities) { -// try { - // on reinitialise tous les validateurs -// for (BeanValidator<?> v : validators.values()) { -// v.setBean(null); -//// v.setContextName(contextName); -// } - for (TopiaEntity e : entities) { - if (log.isDebugEnabled()) { - log.debug("start for entity " + e.getTopiaId()); - } - // détection sur l'entité e - try { - e.accept(this); - } catch (TopiaException e1) { - throw new RuntimeException("could not vist entity " + e.getTopiaId(), e1); - } - } - } - - @Override - public void start(TopiaEntity e) { - if (root == null) { - // start come in start method since - // last clear method invocation - root = e; - addPath(e, "$root", -1); - } - explored.add(e); - SimpleBeanValidator<TopiaEntity> validator = getValidator(e); - if (log.isDebugEnabled()) { - log.debug("with entity " + e.getTopiaId() + " : " + accessorExpression); - } - if (validator != null) { - validator.addSimpleBeanValidatorListener(this); - addEntityInContext(e); - try { - currentRef = new TopiaEntityRef( - root, - e, - accessorExpression.toString(), - path.toArray(new TopiaEntity[path.size()])); - validator.setBean(e); - } finally { - validator.removeSimpleBeanValidatorListener(this); - validator.setBean(null); - } - } - } - - @Override - public void end(TopiaEntity e) { - if (root != null && root.equals(e)) { - // global visit is done - root = null; - removePath(); - } - removeEntityFromContext(e); - } - - private void addEntityInContext(TopiaEntity e) { - - DataContext context = getContext().getDataContext(); - - ObserveEntityEnum anEnum = ObserveEntityEnum.valueOf(e); - switch (anEnum) { - case Route: - context.setSelectedRouteId(e.getTopiaId()); - break; - case TripSeine: { - context.setSelectedTripId(e.getTopiaId()); - Program program = ((TripSeine) e).getProgram(); - if (program != null) { - context.setSelectedProgramId(program.getTopiaId()); - } else { - context.setSelectedProgramId(null); - } - } - break; - case ActivitySeine: - context.setSelectedActivityId(e.getTopiaId()); - break; - case SetSeine: - context.setSelectedSetId(e.getTopiaId()); - break; - case TripLongline: { - context.setSelectedTripId(e.getTopiaId()); - Program program = ((TripLongline) e).getProgram(); - if (program != null) { - context.setSelectedProgramId(program.getTopiaId()); - } else { - context.setSelectedProgramId(null); - } - } - break; - case ActivityLongline: - context.setSelectedActivityId(e.getTopiaId()); - break; - case SetLongline: - context.setSelectedSetId(e.getTopiaId()); - break; - case FloatingObject: - context.setSelectedFloatingObjectId(e.getTopiaId()); - break; - case NonTargetLength: - break; - case TargetLength: - break; - case TransmittingBuoy: - break; - case NonTargetCatch: - break; - case TargetCatch: - break; - case NonTargetSample: - break; - case TargetSample: - break; - case ObjectObservedSpecies: - break; - case SchoolEstimate: - break; - case ObjectSchoolEstimate: - break; - case VesselActivitySeine: - break; - case SurroundingActivity: - break; - case Vessel: - break; - case VesselSizeCategory: - break; - case WeightCategory: - break; - case ReasonForNullSet: - break; - case ReasonForNoFishing: - break; - case SpeciesFate: - break; - case ObjectFate: - break; - case Species: - break; - case SpeciesGroup: - break; - case DetectionMode: - break; - case Person: - break; - case Ocean: - break; - case TransmittingBuoyOperation: - break; - case ObjectOperation: - break; - case Organism: - break; - case LengthWeightParameter: - break; - case Country: - break; - case Program: - break; - case ReasonForDiscard: - break; - case SpeciesStatus: - break; - case ObservedSystem: - break; - case TransmittingBuoyType: - break; - case VesselType: - break; - case ObjectType: - break; - case Wind: - break; - } - } - - private void removeEntityFromContext(TopiaEntity e) { - - DataContext context = getContext().getDataContext(); - - ObserveEntityEnum anEnum = ObserveEntityEnum.valueOf(e); - switch (anEnum) { - case Route: - context.setSelectedRouteId(null); - break; - case TripSeine: - context.setSelectedTripId(null); - context.setSelectedProgramId(null); - break; - case ActivitySeine: - context.setSelectedActivityId(null); - break; - case SetSeine: - context.setSelectedSetId(null); - break; - case TripLongline: - context.setSelectedTripId(null); - context.setSelectedProgramId(null); - break; - case ActivityLongline: - context.setSelectedActivityId(null); - break; - case SetLongline: - context.setSelectedSetId(null); - break; - case FloatingObject: - context.setSelectedFloatingObjectId(null); - break; - case NonTargetLength: - break; - case TargetLength: - break; - case TransmittingBuoy: - break; - case NonTargetCatch: - break; - case TargetCatch: - break; - case NonTargetSample: - break; - case TargetSample: - break; - case ObjectObservedSpecies: - break; - case SchoolEstimate: - break; - case ObjectSchoolEstimate: - break; - case VesselActivitySeine: - break; - case SurroundingActivity: - break; - case Vessel: - break; - case VesselSizeCategory: - break; - case WeightCategory: - break; - case ReasonForNullSet: - break; - case ReasonForNoFishing: - break; - case SpeciesFate: - break; - case ObjectFate: - break; - case Species: - break; - case SpeciesGroup: - break; - case DetectionMode: - break; - case Person: - break; - case Ocean: - break; - case TransmittingBuoyOperation: - break; - case ObjectOperation: - break; - case Organism: - break; - case LengthWeightParameter: - break; - case Country: - break; - case Program: - break; - case ReasonForDiscard: - break; - case SpeciesStatus: - break; - case ObservedSystem: - break; - case TransmittingBuoyType: - break; - case VesselType: - break; - case ObjectType: - break; - case Wind: - break; - } - } - - @Override - public void visit(TopiaEntity e, - String name, - Class<?> type, - Object value) { - TopiaEntity e1 = getTopiaValue(value); - if (e1 != null) { - addPath(e1, name, -1); - try { - try { - e1.accept(this); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error(ex.getMessage(), ex); - } - } - } finally { - removePath(); - } - } - } - - @Override - public void visit(TopiaEntity e, - String name, - Class<?> collectionType, - Class<?> type, - int index, - Object value) { - TopiaEntity e1 = getTopiaValue(value); - if (e1 != null) { - addPath(e1, name, index); - try { - try { - e1.accept(this); - } catch (TopiaException ex) { - if (log.isErrorEnabled()) { - log.error(ex.getMessage(), ex); - } - } - } finally { - removePath(); - } - } - } - - @Override - public void visit(TopiaEntity e, - String name, - Class<?> collectionType, - Class<?> type, - Object value) { - Collection<?> cValue = (Collection<?>) value; - if (TopiaEntity.class.isAssignableFrom(type) && - cValue != null && !cValue.isEmpty()) { - int i = 0; - for (Object currentValue : cValue) { - visit(e, name, collectionType, type, i++, currentValue); - } - } - } - - public SortedMap<TopiaEntityRef, List<SimpleBeanValidatorMessage<?>>> getRefs() { - // on renvoie toujours une copie - // pour pouvoir au plus tôt nettoyer le detecteur - TreeMap<TopiaEntityRef, List<SimpleBeanValidatorMessage<?>>> result; - result = new TreeMap<TopiaEntityRef, List<SimpleBeanValidatorMessage<?>>>(refs); - return result; - } - - @Override - public void clear() { - path.clear(); - refs.clear(); - root = null; - explored.clear(); - accessorExpression.setLength(0); - } - - protected TopiaEntity getTopiaValue(Object value) { - TopiaEntity topiaEntity = (TopiaEntity) (value != null && - value instanceof TopiaEntity ? value : null); - if (topiaEntity != null && explored.contains(topiaEntity)) { - // entite deja visitee - topiaEntity = null; - } - return topiaEntity; - } - - protected <T extends TopiaEntity> SimpleBeanValidator<T> getValidator(T e) { - Class<T> contractClass; - contractClass = (Class<T>) ObserveDAOHelper.getContractClass(e.getClass()); - return validators.getValidator(contractClass); - } - - protected void addPath(TopiaEntity e, String name, int index) { - path.add(e); - if (accessorExpression.length() > 0) { - accessorExpression.append(SEPARATOR); - } - accessorExpression.append(name); - if (index > -1) { - accessorExpression.append("[@topiaId=\""); - accessorExpression.append(e.getTopiaId()); - accessorExpression.append("\"]"); - } - if (log.isTraceEnabled()) { - log.trace("add to stack : " + e.getTopiaId() + ", new size : " + - path.size() + ", path : " + accessorExpression); - } - } - - protected void removePath() { - TopiaEntity e = path.removeLast(); - if (path.isEmpty()) { - accessorExpression.setLength(0); - } else { - int index = accessorExpression.lastIndexOf(SEPARATOR); - if (index > -1) { - accessorExpression.delete(index, - accessorExpression.length()); - } - } - if (log.isTraceEnabled()) { - log.trace("remove from stack : " + e.getTopiaId() + - ", new size : " + path.size() + ", path : " + - accessorExpression); - } - } - - @Override - public void onFieldChanged(SimpleBeanValidatorEvent event) { - SimpleBeanValidator<?> validator = event.getSource(); - - // on ne traite que les messages a ajouter - String[] messagesToAdd = event.getMessagesToAdd(); - - if (messagesToAdd == null || messagesToAdd.length == 0) { - return; - } - - if (log.isDebugEnabled()) { - log.debug("will add " + Arrays.toString(messagesToAdd) + - " for " + currentRef.getAccessorExpression()); - } - List<SimpleBeanValidatorMessage<?>> list = refs.get(currentRef); - if (list == null) { - // first time for this entity - list = new ArrayList<SimpleBeanValidatorMessage<?>>(); - refs.put(currentRef, list); - } - for (String m : messagesToAdd) { - SimpleBeanValidatorMessage<?> message; - message = new SimpleBeanValidatorMessage( - validator, - event.getField(), - m, - event.getScope()); - if (log.isDebugEnabled()) { - log.debug("add message " + message); - } - list.add(message); - } - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/validation/ValidationModelMode.java b/observe-business/src/main/java/fr/ird/observe/validation/ValidationModelMode.java deleted file mode 100644 index 938f3a3..0000000 --- a/observe-business/src/main/java/fr/ird/observe/validation/ValidationModelMode.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.validation; - -import fr.ird.observe.entities.Entities; -import fr.ird.observe.ObserveEntityEnum; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser le type de modele de validation a utiliser. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public enum ValidationModelMode { - - /** validation du referentiel */ - REFERENTIEL( - n("observe.validation.model.type.referentiel"), - n("observe.validation.model.type.referentiel.description"), - Entities.REFERENCE_ENTITIES - ), - - /** validation de donnees observer */ - DATA( - n("observe.validation.model.type.data"), - n("observe.validation.model.type.data.description"), - Entities.DATA_ENTITIES - ), - - /** validation du referentiel et de donnees observer */ - ALL( - n("observe.validation.model.type.all"), - n("observe.validation.model.type.all.description"), - Entities.ALL_ENTITIES - ); - - private final String label; - - private final String description; - - private final Class<? extends TopiaEntity>[] contracts; - - ValidationModelMode(String label, - String description, - ObserveEntityEnum... contracts) { - this.label = label; - this.description = description; - this.contracts = TopiaEntityHelper.getContracts(contracts); - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } - - public Class<? extends TopiaEntity>[] getContracts() { - return contracts; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/validation/ValidationService.java b/observe-business/src/main/java/fr/ird/observe/validation/ValidationService.java deleted file mode 100644 index 1407e64..0000000 --- a/observe-business/src/main/java/fr/ird/observe/validation/ValidationService.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.validation; - -import fr.ird.observe.ObserveEntityEnum; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.bean.simple.SimpleBeanValidator; - -import java.util.Set; - -/** - * Contrat du service de validation des données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class ValidationService { - - /** Logger */ - private static final Log log = - LogFactory.getLog(ValidationService.class); - - /** - * Obtenir le validateur d'un type objet - * - * @param context le lastName du context de validation - * @param scopes les scopes autorisés - * @param klass type de l'objet à valider - * @param <B> type de l'objet à valider - * @return le validateur trouvé ou {@code null} - */ - public <B> SimpleBeanValidator<B> getValidator(String context, - NuitonValidatorScope[] scopes, - Class<B> klass) { - - SimpleBeanValidator<B> valitator = SimpleBeanValidator.newValidator( - klass, - context, - scopes - ); - - Set<NuitonValidatorScope> resultScopes = valitator.getEffectiveScopes(); - if (resultScopes.isEmpty()) { - valitator = null; - if (log.isDebugEnabled()) { - log.debug(klass + " : validator skip (no scopes detected)"); - } - } else { - if (log.isDebugEnabled()) { - log.debug(klass + " : keep validator " + valitator); - } - } - return valitator; - } - - /** - * Obtenir le dictionnaire des validateurs pour les types d'entités donnés. - * - * @param contextName le lastName du context de validation - * @param scopes les scopes autorisés - * @param beanclass types des entités - * @return le dictionnaire des validateurs par type d'entité. - */ - public ValidatorsMap getValidators( - String contextName, - NuitonValidatorScope[] scopes, - Class<?>... beanclass) { - ValidatorsMap map = detectValidators( - contextName, - scopes, - beanclass - ); - return map; - } - - /** - * Obtenir le dictionnaire des validateurs pour les entités donnés. - * <p/> - * <b>Note:</b> On effectue un parcours des entités pour connaitre les types - * d'objets à valider, il faut donc des les collections des entités soient - * toutes chargées (ou l'objet attaché à une transaction...). - * - * @param contextName le lastName du context de validation - * @param scopes les scopes autorisés - * @param entities les entités - * @return le dictionnaire des validateurs par type d'entité. - */ - public ValidatorsMap getValidators( - String contextName, - NuitonValidatorScope[] scopes, - TopiaEntity... entities) { - - Set<Class<? extends TopiaEntity>> types; - try { - types = TopiaEntityHelper.detectTypes( - ObserveEntityEnum.values(), - entities - ); - } catch (TopiaException e) { - throw new IllegalArgumentException( - "could not obtains types for reason " + e.getMessage(), e); - } - - ValidatorsMap result = detectValidators( - contextName, - scopes, - types.toArray(new Class<?>[types.size()]) - ); - return result; - } - - @SuppressWarnings("unchecked") - public <T> ValidatorsMap detectValidators( - String context, - NuitonValidatorScope[] scopes, - Class<?>... types) { - - ValidatorsMap result = new ValidatorsMap(); - - for (Class<?> c : types) { - // on cherche le validateur - SimpleBeanValidator<T> validator = (SimpleBeanValidator<T>) - getValidator(context, scopes, c); - if (validator != null) { - // on enregistre le validateur - result.put(c, validator); - } - } - return result; - } -} diff --git a/observe-business/src/main/java/fr/ird/observe/validation/ValidatorsMap.java b/observe-business/src/main/java/fr/ird/observe/validation/ValidatorsMap.java deleted file mode 100644 index b040f4c..0000000 --- a/observe-business/src/main/java/fr/ird/observe/validation/ValidatorsMap.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 CodeLutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.validation; - -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.bean.simple.SimpleBeanValidator; - -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Un dictionnaire de validateurs ordonnees par le type de leur bean. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.1 - */ -public class ValidatorsMap implements Map<Class<?>, SimpleBeanValidator<?>> { - - protected final Map<Class<?>, SimpleBeanValidator<?>> delegate; - - public ValidatorsMap() { - delegate = new HashMap<Class<?>, SimpleBeanValidator<?>>(); - } - - public NuitonValidatorScope[] getScopes() { - EnumSet<NuitonValidatorScope> result = - EnumSet.noneOf(NuitonValidatorScope.class); - for (SimpleBeanValidator<?> b : values()) { - result.addAll(b.getScopes()); - } - return result.toArray(new NuitonValidatorScope[result.size()]); - } - - public <X> SimpleBeanValidator<X> getValidator(Class<X> klass) { - SimpleBeanValidator<X> beanValidator = (SimpleBeanValidator<X>) get(klass); - return beanValidator; - } - - @Override - public int size() { - return delegate.size(); - } - - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - @Override - public boolean containsKey(Object key) { - return delegate.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - return delegate.containsValue(value); - } - - @Override - public SimpleBeanValidator<?> get(Object key) { - return delegate.get(key); - } - - @Override - public SimpleBeanValidator<?> put(Class<?> key, SimpleBeanValidator<?> value) { - return delegate.put(key, value); - } - - @Override - public SimpleBeanValidator<?> remove(Object key) { - return delegate.remove(key); - } - - @Override - public void putAll(Map<? extends Class<?>, ? extends SimpleBeanValidator<?>> m) { - delegate.putAll(m); - } - - @Override - public void clear() { - delegate.clear(); - } - - @Override - public Set<Class<?>> keySet() { - return delegate.keySet(); - } - - @Override - public Collection<SimpleBeanValidator<?>> values() { - return delegate.values(); - } - - @Override - public Set<Entry<Class<?>, SimpleBeanValidator<?>>> entrySet() { - return delegate.entrySet(); - } - -} diff --git a/observe-business/src/main/resources/META-INF/services/fr.ird.observe.business.db.DataSourceProvider b/observe-business/src/main/resources/META-INF/services/fr.ird.observe.business.db.DataSourceProvider deleted file mode 100644 index 0310627..0000000 --- a/observe-business/src/main/resources/META-INF/services/fr.ird.observe.business.db.DataSourceProvider +++ /dev/null @@ -1,2 +0,0 @@ -fr.ird.observe.business.db.impl.H2DataSourceProvider -fr.ird.observe.business.db.impl.PGDataSourceProvider diff --git a/observe-business/src/main/resources/META-INF/services/fr.ird.observe.report.model.ReportOperation b/observe-business/src/main/resources/META-INF/services/fr.ird.observe.report.model.ReportOperation deleted file mode 100644 index a15219d..0000000 --- a/observe-business/src/main/resources/META-INF/services/fr.ird.observe.report.model.ReportOperation +++ /dev/null @@ -1,6 +0,0 @@ -fr.ird.observe.report.model.operations.SumIntColumn -fr.ird.observe.report.model.operations.SumColumn -fr.ird.observe.report.model.operations.SumIntRow -fr.ird.observe.report.model.operations.SumRow -fr.ird.observe.report.model.operations.ExecuteRequests -fr.ird.observe.report.model.operations.GroupByLength \ No newline at end of file diff --git a/observe-business/src/main/resources/faunaminmax.csv b/observe-business/src/main/resources/faunaminmax.csv deleted file mode 100644 index 6c8fd3f..0000000 --- a/observe-business/src/main/resources/faunaminmax.csv +++ /dev/null @@ -1,164 +0,0 @@ -"code3L","Nombre propio","Nombre comun","grupo","longueurMin","longueurMax","poidsMax","grlmin","grlmax","grpmin","grpmax" -"ANA","Aetobatus narinari","Chucho pintado",2,0,0,0,10,700,10,800000 -"APE","Alopias pelagicus","Zorro pelaico",2,0,0,0,10,700,10,800000 -"ASU","Alopias superciliosus","Zorro oj",2,0,0,0,10,700,10,800000 -"AVA","Abudefduf vaigiensis",,3,0,0,0,10,200,10,50000 -"AVU","Alopias vulpinus","Zorro",2,0,0,0,10,700,10,800000 -"BAC","Balaenoptera acutorostra","Rorcual enano / Rorcual aliblan",5,0,0,0,10,5000,10,9999999 -"BAE","Abalistes stellatus","Pejepuerco estrellado",3,35,60,0,10,200,10,50000 -"BAL","Balistes carolinensis","Pez ballesta",3,29,60,6150,10,200,10,50000 -"BAP","Balistes punctatus","Pejepuerco moteado",3,10,60,0,10,200,10,50000 -"BAS","Aluterus scriptus",,3,33,49,0,10,200,10,50000 -"BAT","Aluterus monoceros",,3,24,76,2710,10,200,10,50000 -"BBO","Balaenoptera borealis","Rorcual del norte",5,0,0,0,10,5000,10,9999999 -"BCM","Canthidermis maculatus",,3,21,50,0,10,200,10,50000 -"BEA","Ablennesse hians",,3,74,140,4800,10,200,10,50000 -"BED","Balaenoptera edeni","Rorcual tropical",5,0,0,0,10,5000,10,9999999 -"BLM","Makaira indica","Aguja negra",1,188,465,750000,10,500,10,906000 -"BMU","Balaenoptera musculus","Ballena azul",5,0,0,0,10,5000,10,9999999 -"BON","Sarda sarda","Bonito",3,20,85,0,10,200,10,50000 -"BPH","Balaenoptera physalus","Rorcual comun",5,0,0,0,10,5000,10,9999999 -"BRA","Familia Bramidae",,3,0,0,0,10,200,10,50000 -"BUM","Makaira nigricans","Aguja azul",1,100,500,820000,10,500,10,906000 -"CCA","Carcharodon carcharias","Jaqueton blanco",2,0,0,0,10,700,10,800000 -"CCC","Caretta caretta","Tortuga boba / caguama",4,20,125,0,10,600,10,190000 -"CEX",,"Cetaeo no identificado",5,0,0,0,10,5000,10,9999999 -"CFA","Carcharhinus falciformis","Jaqueton",2,53,350,346000,10,700,10,800000 -"CLM","Decapterus macarellus",,3,17,47,0,10,200,10,50000 -"CLO","Carcharhinus longimanus","Tiburon oceanico",2,67,396,167400,10,700,10,800000 -"CMM","Chelonia mydas","Tortuga verde",4,39,150,0,10,600,10,190000 -"COE","Coryphaena equiselis","Dorado",3,20,127,0,10,200,10,50000 -"COH","Coryphaena hippurus","Lampuga /Dorado comun",3,20,210,40000,10,200,10,50000 -"COR","Carangoides orthogrammus",,3,22,28,0,10,200,10,50000 -"CRS","Caranx sexfasciatus",,3,18,66,0,10,200,10,50000 -"CRY","Caranx crysos","Cojinua negra",3,20,100,0,10,200,10,50000 -"CUH","Uraspis helvola",,3,12,54,0,10,200,10,50000 -"CUS","Uraspis secunda","Jurel volantin",3,20,50,2040,10,200,10,50000 -"DCC","Dermochelys coriacea","Tortuga laud",4,50,190,0,10,600,10,190000 -"DDE","Delphinus delphis","Delfin comun",5,0,0,0,10,5000,10,9999999 -"DIH","Diodon hystrix","Pez erizo",3,12,91,2800,10,200,10,50000 -"DIO","Familia Diodontidae",,3,0,0,0,10,200,10,50000 -"DVI","Pteroplatytrygon violace","Chucho",2,36,0,0,10,700,10,800000 -"EIM","Eretmochelys imbricata","Tortuga carey",4,18,90,0,10,600,10,190000 -"ELP","Elagatis bipinnulata","Macarela salmon",3,20,180,46200,10,200,10,50000 -"EPL","Phtheirichthys lineatus",,3,0,76,0,10,200,10,50000 -"ETM","G駭ero Etmopterus",,2,0,0,0,10,700,10,800000 -"FAL","Familia Alopiidae",,2,0,0,0,10,700,10,800000 -"FAT","Feresa attenuata","Orca pigmea",5,0,0,0,10,5000,10,9999999 -"FBA","Familia Balistidae",,3,27,75,0,10,200,10,50000 -"FBL","Familia Belonidae",,3,81,153,0,10,200,10,50000 -"FCA","Familia Carcharhinidae",,2,0,0,0,10,700,10,800000 -"FCO","Familia Coryphaenidae",,3,62,80,0,10,200,10,50000 -"FCR","Familia Carangidae",,3,17,0,0,10,200,10,50000 -"FDA","Familia Dasyatidae",,2,38,320,0,10,700,10,800000 -"FEC","Familia Echeneidae",,3,0,0,0,10,200,10,50000 -"FEP","Familia Ephippidae",,3,0,0,0,10,200,10,50000 -"FEV","Euleptorhamphosus velox",,3,0,0,0,10,200,10,50000 -"FEX","Familia Exocoetidae",,3,15,41,0,10,200,10,50000 -"FFI","Familia Fistularidae",,3,0,0,0,10,200,10,50000 -"FIS","Familia Istiophoridae",,1,0,500,0,10,500,10,906000 -"FKY","Kyphosus sp.",,3,25,90,0,10,200,10,50000 -"BMM","Makaira mazara",,1,0,500,906000,10,500,10,906000 -"CUX","Uraspis sp",,3,0,55,3000,10,200,10,50000 -"FOD","Familia Odontaspididae",,2,0,370,300000,10,700,10,800000 -"FLA","Familia Lamnidae",,2,0,0,0,10,700,10,800000 -"FMO","Familia Molidae",,3,0,0,0,10,200,10,50000 -"FPO","Familia Pomacentridae",,3,0,6,0,10,200,10,50000 -"FRH","Familia Rhincodontidae",,2,0,0,0,10,700,10,800000 -"FSC","Familia Scombridae",,3,0,0,0,10,200,10,50000 -"FSE","Familia Serranidae",,3,0,0,0,10,200,10,50000 -"FSP","Familia Sphyrnidae",,2,0,300,0,10,700,10,800000 -"FTT","Familia Tetraodontidae",,3,0,0,0,10,200,10,50000 -"GCU","Galeocerdo cuvieri","Tintorera",2,0,0,0,10,700,10,800000 -"GGR","Grampus griseus","Delfin de Risso / Delfin gris",5,0,0,0,10,5000,10,9999999 -"GMA","Globicephala macrorhynch","Calderon aletas cortas/C. Tropi",5,0,0,0,10,5000,10,9999999 -"GME","Globicephala melas","Calderon comun",5,0,0,0,10,5000,10,9999999 -"IBR","Isistius brasiliensis",,2,0,0,0,10,700,10,800000 -"IOX","Isurus oxyrinchus","Marrajo dientuso",2,183,400,505800,10,700,10,800000 -"KBR","Kogia breviceps","Cachalote pigmeo",5,0,0,0,10,5000,10,9999999 -"KPC","Kyphosus cinerascens",,3,15,51,0,10,200,10,50000 -"KPS","Kyphosus sectator","Chopon",3,20,76,6010,10,200,10,50000 -"KPV","Kyphosus vaigiensis",,3,0,0,0,10,200,10,50000 -"KSI","Kogia simus","Cachalote enano",5,0,0,0,10,5000,10,9999999 -"LAG","Lampris guttatus","Luna real",3,0,200,270000,10,200,10,50000 -"LAM","Familia Lampridae",,3,0,0,0,10,200,10,50000 -"LHO","Lagenodelphis hosei","Delfin de Fraser",5,0,0,0,10,5000,10,9999999 -"LKE","Lepidochelis kempii","Tortuga de Kemp / lora",4,0,70,0,10,600,10,190000 -"LLA","Lagocephalus lagocephalu","s",3,38,48,0,10,200,10,50000 -"LOB","Lobotes surinamensis","Dormilona",3,20,110,19200,10,200,10,50000 -"LOL","Lepidochelis olivacea","Tortuga bastarda / golfina",4,0,74,0,10,600,10,190000 -"MAL","Masturus lanceolatus","Pez luna",3,0,337,0,10,200,10,50000 -"MAQ","Myliobatis aquila","Aguila marina",2,0,0,0,10,700,10,800000 -"MAW","Scomberomorus tritor","Carite pintado",3,0,0,0,10,200,10,50000 -"MBA","Manta birostris","Manta gigante",2,100,800,0,10,700,10,800000 -"MCO","Mobula tarapacana","Diablo gigante de Guinea",2,100,300,0,10,700,10,800000 -"MDE","Mesoplodon densirostris","Zifio de Blainville",5,0,0,0,10,5000,10,9999999 -"MEU","Mesoplodon europaeus","Zifio de Gervais",5,0,0,0,10,5000,10,9999999 -"MMO","Mola mola","Pez luna",3,90,333,0,10,200,10,50000 -"MNO","Megaptera novaeangliae","Rorcual jorobado / Ballena joro",5,0,0,0,10,5000,10,9999999 -"MOM","Mobula mobular","Manta",2,100,520,0,10,700,10,800000 -"MPE","Megachasma pelagios","Tiburon boca grande",2,0,0,0,10,700,10,800000 -"MRA","Mobula japanica",,2,0,0,0,10,700,10,800000 -"MYS",,"Misticeto no identificado",5,0,0,0,10,5000,10,9999999 -"NAD","Naucrates ductor","Pez piloto",3,10,70,0,10,200,10,50000 -"OCA","Orden Carcharihiniformes",,2,0,0,0,10,700,10,800000 -"ODO",,"Odontoceto no identificado",5,0,0,0,10,5000,10,9999999 -"OHT","Orden Heterodontiformes",,2,0,0,0,10,700,10,800000 -"OHX","Orden Hexanchiformes",,2,0,0,0,10,700,10,800000 -"OLA","Orden Lamniformes",,2,0,0,0,10,700,10,800000 -"OOE","Orden Orectolobiformes",,2,0,0,0,10,700,10,800000 -"OOR","Orcinus orca","Orca",5,0,0,0,10,5000,10,9999999 -"OPR","Orden Pristiophoriformes",,2,0,0,0,10,700,10,800000 -"OSR","Orden Squaliformes",,2,0,0,0,10,700,10,800000 -"OST","Orden Squatiniformes",,2,0,0,0,10,700,10,800000 -"PCR","Pseudorca crassidens","Orca falsa",5,0,0,0,10,5000,10,9999999 -"PEP","Peponocephala electra","Calderon pequeño",5,0,0,0,10,5000,10,9999999 -"PGL","Prionace glauca","Tiburon azul",2,0,400,205900,10,700,10,800000 -"PLS","Platax sp.",,3,17,46,0,10,200,10,50000 -"PLT","Platax teira",,3,0,0,0,10,200,10,50000 -"PMA","Physeter macrocephalus","Cachalote",5,0,0,0,10,5000,10,9999999 -"RAL","Ranzania laevis",,3,0,0,0,10,200,10,50000 -"RAU","Remora australis",,3,0,0,0,10,200,10,50000 -"RAX",,"Raya no identificada",2,0,0,0,10,700,10,800000 -"REA","Remorina albescens",,3,0,76,0,10,200,10,50000 -"REM","Remora remora","Remora",3,25,87,1070,10,200,10,50000 -"REX",,"Tiburon no identificado",2,130,130,0,10,700,10,800000 -"RHI","SubFamilia Rhinopteridae",,2,0,0,0,10,700,10,800000 -"RHS","Rhinoptera sp","Gavilan",2,0,0,0,10,700,10,800000 -"RPE","Cetorhinus maximus","Tiburon peregrino",2,0,0,0,10,700,10,800000 -"RTY","Rhincodon typus","Tiburon ballena",2,0,2000,0,10,700,10,800000 -"RUP","Ruvettus pretiosus","Escolar clavo",3,0,200,63500,10,200,10,50000 -"SAI","Istiophorus albicans","Pez vela del Atlantico",1,100,315,58100,10,500,10,906000 -"SAP","Istiophorus platypterus","Pez vela del Indico",1,0,348,100200,10,500,10,906000 -"SAT","Stenella attenuata","Estenela moteada / Delfin manch",5,0,0,0,10,5000,10,9999999 -"SBR","Steno bredanensis","Esteno / Delfin dientes rugosos",5,0,0,0,10,5000,10,9999999 -"SCL","Stenella clymene","Delfin clymene",5,0,0,0,10,5000,10,9999999 -"SCO","Stenella coeruleoalba","Estenela listada / Delfin lista",5,0,0,0,10,5000,10,9999999 -"SDX","Decapterus sp.",,3,28,45,0,10,200,10,50000 -"SER","Seriola rivoliana","Pez limon",3,28,160,59900,10,200,10,50000 -"SFR","Stenella frontalis","Delfin pintado",5,0,0,0,10,5000,10,9999999 -"SHS","Tetrapturus angustirostr","Marlin trompa corta",1,155,230,52000,10,500,10,906000 -"SJA","Scomber japonicus","Caballa",3,0,0,0,10,200,10,50000 -"SLE","Sphyrna lewini","Cornuda comun",2,100,430,152400,10,700,10,800000 -"SLO","Stenella longirostris","Estenela giradora / Delfin torn",5,0,0,0,10,5000,10,9999999 -"SMO","Sphyrna mokarran","Cornuda gigante",2,0,610,449500,10,700,10,800000 -"SPB","Sphyraena barracuda","Barracuda",3,40,200,50000,10,200,10,50000 -"SPF","Tetrapturus pfluegeri","Aguja picuda",1,0,254,58000,10,500,10,906000 -"SPH","Familia Sphyraenidae",,3,0,0,0,10,200,10,50000 -"SSC","Scomber scombrus","Caballa",3,0,0,0,10,200,10,50000 -"STE",,"Delfin no identificado",5,0,0,0,10,5000,10,9999999 -"STM","Tetrapturus audax","Marlin rayado",1,133,420,440000,10,500,10,906000 -"SWO","Xiphias gladius","Pez espada",1,0,455,650000,10,500,10,906000 -"SZY","Sphyrna zygaena","Cornuda cruz / Pez martillo",2,165,500,400000,10,700,10,800000 -"TCC","Tylosurus crocodilus",,3,0,0,0,10,200,10,50000 -"TOE",,,4,0,0,0,10,600,10,190000 -"TOX",,,4,0,0,0,10,600,10,190000 -"TTR","Tursiops truncatus","Tursio / Delfin mular",5,0,0,0,10,5000,10,9999999 -"WAH","Acanthocybium solandri","Peto",3,40,250,83000,10,200,10,50000 -"WHM","Tetrapturus albidus","Aguja blanca",1,0,300,82500,10,500,10,906000 -"ZAC","Zanclus cornutus",,3,0,0,0,10,200,10,50000 -"ZCA","Ziphius cavirostris","Zifio de Cuvier",5,0,0,0,10,5000,10,9999999 -"BMM","Makaira mazara","Marlin del Indo-Pacifico",1,0,500,906000,10,500,10,906000 -"CUX","Uraspis sp",,3,0,55,3000,10,200,10,50000 -"FOD","Familia Odontaspididae",,2,0,370,300000,10,700,10,800000 -"COI","Carangoides orthogrammus","jurel isleño",3,0,75,7000,10,200,10,50000 diff --git a/observe-business/src/main/resources/i18n/observe-business_en_GB.properties b/observe-business/src/main/resources/i18n/observe-business_en_GB.properties deleted file mode 100644 index 4a1d43f..0000000 --- a/observe-business/src/main/resources/i18n/observe-business_en_GB.properties +++ /dev/null @@ -1,234 +0,0 @@ -nuitonutil.error.convertor.noValue= -nuitonutil.error.float.convertor= -nuitonutil.error.no.convertor= -observe.common.activityLongline=Activity -observe.common.activitySeine=Activity -observe.common.baitHaulingStatus= -observe.common.baitSettingStatus= -observe.common.baitType=Bait type -observe.common.baitsComposition= -observe.common.basket=Basket -observe.common.branchline=Branchline -observe.common.branchlineLength= -observe.common.branchlinesComposition= -observe.common.catchFateLongline= -observe.common.catchLongline=Catches -observe.common.catchWeight= -observe.common.country=Country -observe.common.detectionMode=Detection mode -observe.common.encounter=Encounter -observe.common.encounterType= -observe.common.faoCode=FAO code -observe.common.floatingObject= -observe.common.floatline1Length= -observe.common.floatline2Length= -observe.common.floatlineLengths= -observe.common.floatlinesComposition= -observe.common.fpaZone= -observe.common.gear=Gear -observe.common.gearCaracteristic=Gear caracteristic -observe.common.gearCaracteristicType=Gear caracteristic type -observe.common.gearUseFeaturesLongline= -observe.common.gearUseFeaturesSeine= -observe.common.gender=Gender -observe.common.gps.activity= -observe.common.gps.gpsPoint= -observe.common.gps.gpsPointInterval= -observe.common.harbour=Harbour -observe.common.haulingIdentifier= -observe.common.healthness= -observe.common.homeId=Home Id -observe.common.hookPosition= -observe.common.hookSize= -observe.common.hookType= -observe.common.hooksComposition= -observe.common.id= -observe.common.inconnu= -observe.common.itemHorizontalPosition= -observe.common.itemVerticalPosition= -observe.common.lengthWeightFormula= -observe.common.lengthWeightParameter=Length-weight relationship -observe.common.lightsticksColor=Lightsticks color -observe.common.lightsticksType=Lightsticks type -observe.common.lineType=Line type -observe.common.locode=Locode -observe.common.maturityStatus=Maturity status -observe.common.meanWeight=Mean weight -observe.common.mitigationType=Mitigation type -observe.common.name=Name -observe.common.nocode=No code -observe.common.nonTargetCatch= -observe.common.nonTargetLength= -observe.common.nonTargetSample= -observe.common.none=None -observe.common.objectFate= -observe.common.objectObservedSpecies= -observe.common.objectOperation= -observe.common.objectSchoolEstimate= -observe.common.objectType= -observe.common.observedSystem= -observe.common.observerLabel= -observe.common.ocean=Ocean -observe.common.ocean/label1= -observe.common.ocean/label2= -observe.common.ocean/label3= -observe.common.ocean/label4= -observe.common.ocean/label5= -observe.common.ocean/label6= -observe.common.ocean/label7= -observe.common.ocean/label8= -observe.common.oldCode3L= -observe.common.organism=Organisme -observe.common.person=Person -observe.common.program=Program -observe.common.reasonForDiscard=Reason for discard -observe.common.reasonForNoFishing=Reason for no fishing -observe.common.reasonForNullSet=Reason for null set -observe.common.route=Road -observe.common.schoolEstimate= -observe.common.scientificLabel=Genuis name -observe.common.section= -observe.common.sensorBrand=Sensor brand -observe.common.sensorDataFormat= -observe.common.sensorPosition=Sensor position -observe.common.sensorType=Sensor type -observe.common.sensorUsed=Sensor used -observe.common.setLongline=Fishing operation -observe.common.setSeine=Set -observe.common.settingIdentifier=Setting identifier -observe.common.settingShape=Setting shape -observe.common.sex=sex -observe.common.sizeMeasure=Size measure -observe.common.sizeMeasureType=Size measure type -observe.common.species=Specy -observe.common.species/scientificLabel= -observe.common.speciesFate= -observe.common.speciesGroup= -observe.common.speciesList= -observe.common.speciesStatus=Species status -observe.common.stomacFullness=Stomac fullness -observe.common.surroundingActivity= -observe.common.targetCatch= -observe.common.targetLength= -observe.common.targetSample= -observe.common.tdr=TDR -observe.common.tdrRecord= -observe.common.time=Time -observe.common.totalCount= -observe.common.tracelineLength= -observe.common.transmittingBuoy= -observe.common.transmittingBuoyOperation= -observe.common.transmittingBuoyType= -observe.common.tripLongline=Trip -observe.common.tripSeine=Trip -observe.common.tripType=Trip type -observe.common.vessel=Boat -observe.common.vessel/label1=Boat -observe.common.vessel/label2=Boat -observe.common.vessel/label3=Boat -observe.common.vessel/label4=Boat -observe.common.vessel/label5=Boat -observe.common.vessel/label6=Boat -observe.common.vessel/label7=Boat -observe.common.vessel/label8=Boat -observe.common.vesselActivityLongline= -observe.common.vesselActivitySeine= -observe.common.vesselActivitySeine/label1= -observe.common.vesselActivitySeine/label2= -observe.common.vesselActivitySeine/label3= -observe.common.vesselActivitySeine/label4= -observe.common.vesselActivitySeine/label5= -observe.common.vesselActivitySeine/label6= -observe.common.vesselActivitySeine/label7= -observe.common.vesselActivitySeine/label8= -observe.common.vesselSizeCategory= -observe.common.vesselType= -observe.common.weightCategory= -observe.common.weightMeasure= -observe.common.weightMeasureType= -observe.common.wind= -observe.message.consolidate.computed.taille= -observe.message.consolidate.computed.weight= -observe.message.consolidate.maree.need.update= -observe.message.consolidate.no.activity.from.maree= -observe.message.consolidate.no.parametrage.found= -observe.message.consolidate.nothing.to.save.for.maree= -observe.message.consolidate.start.activity= -observe.message.consolidate.start.maree= -observe.service.build.synchro.referentiel= -observe.storage.connexionStatut.failed= -observe.storage.connexionStatut.failed.description= -observe.storage.connexionStatut.success= -observe.storage.connexionStatut.success.description= -observe.storage.connexionStatut.untested= -observe.storage.connexionStatut.untested.description= -observe.storage.creationMode.empty= -observe.storage.creationMode.empty.description= -observe.storage.creationMode.externalDump= -observe.storage.creationMode.externalDump.description= -observe.storage.creationMode.importLocalStorage= -observe.storage.creationMode.importLocalStorage.description= -observe.storage.creationMode.importRemoteStorage= -observe.storage.creationMode.importRemoteStorage.description= -observe.storage.creationMode.internalDump= -observe.storage.creationMode.internalDump.description= -observe.storage.dataPolicy.data= -observe.storage.dataPolicy.no.wrights= -observe.storage.dataPolicy.read= -observe.storage.dataPolicy.readData= -observe.storage.dataPolicy.readData.description= -observe.storage.dataPolicy.readReferentiel= -observe.storage.dataPolicy.readReferentiel.description= -observe.storage.dataPolicy.readWrite= -observe.storage.dataPolicy.referentiel= -observe.storage.dataPolicy.write= -observe.storage.dataPolicy.writeData= -observe.storage.dataPolicy.writeData.description= -observe.storage.dataPolicy.writeReferentiel= -observe.storage.dataPolicy.writeReferentiel.description= -observe.storage.database.higher.than.application=You database is in higher version (%s). ObServe version (%s) can not open it. Please get the last version of the software. -observe.storage.db.version= -observe.storage.dbMode.createLocal= -observe.storage.dbMode.createLocal.description= -observe.storage.dbMode.useLocal= -observe.storage.dbMode.useLocal.description= -observe.storage.dbMode.useRemote= -observe.storage.dbMode.useRemote.description= -observe.storage.error.import.referentiel= -observe.storage.error.newConfig= -observe.storage.error.newService= -observe.storage.h2.login= -observe.storage.label.local= -observe.storage.message.closed= -observe.storage.message.closing= -observe.storage.message.create.from.script= -observe.storage.message.create.schema= -observe.storage.message.import.data.from= -observe.storage.message.import.data.to= -observe.storage.message.import.referentiel.done= -observe.storage.message.import.referentiel.from= -observe.storage.message.import.referentiel.to= -observe.storage.message.launch.migration= -observe.storage.message.opened= -observe.storage.message.opening= -observe.storage.message.provider.detected= -observe.storage.message.replicate.data.entity= -observe.storage.message.replicate.data.no.data= -observe.storage.message.replicate.entities.done= -observe.storage.message.replicate.entities.starting= -observe.storage.message.replicate.referentiel.done= -observe.storage.message.replicate.referentiel.starting= -observe.storage.message.storeDB= -observe.storage.remote.isUsingSll= -observe.storage.remote.login= -observe.storage.remote.url= -observe.storage.remote.wrights= -observe.storage.unversionned.db= -observe.synchro.obsolete.entity.label= -observe.synchro.obsolete.entity.ref= -observe.validation.model.type.all= -observe.validation.model.type.all.description= -observe.validation.model.type.data= -observe.validation.model.type.data.description= -observe.validation.model.type.referentiel= -observe.validation.model.type.referentiel.description= diff --git a/observe-business/src/main/resources/i18n/observe-business_es_ES.properties b/observe-business/src/main/resources/i18n/observe-business_es_ES.properties deleted file mode 100644 index 729e862..0000000 --- a/observe-business/src/main/resources/i18n/observe-business_es_ES.properties +++ /dev/null @@ -1,234 +0,0 @@ -nuitonutil.error.convertor.noValue= -nuitonutil.error.float.convertor= -nuitonutil.error.no.convertor= -observe.common.activityLongline=Actividad -observe.common.activitySeine=Actividad -observe.common.baitHaulingStatus= -observe.common.baitSettingStatus= -observe.common.baitType= -observe.common.baitsComposition= -observe.common.basket= -observe.common.branchline= -observe.common.branchlineLength= -observe.common.branchlinesComposition= -observe.common.catchFateLongline= -observe.common.catchLongline= -observe.common.catchWeight=Peso estimado (en t) -observe.common.country=País -observe.common.detectionMode=Modo de detección -observe.common.encounter= -observe.common.encounterType= -observe.common.faoCode=FAO coda -observe.common.floatingObject=Objeto flotante -observe.common.floatline1Length= -observe.common.floatline2Length= -observe.common.floatlineLengths= -observe.common.floatlinesComposition= -observe.common.fpaZone= -observe.common.gear= -observe.common.gearCaracteristic= -observe.common.gearCaracteristicType= -observe.common.gearUseFeaturesLongline= -observe.common.gearUseFeaturesSeine= -observe.common.gender=Sexo -observe.common.gps.activity=Actividad -observe.common.gps.gpsPoint=Punto GPS -observe.common.gps.gpsPointInterval=Intervalo de puntos -observe.common.harbour=Puerto -observe.common.haulingIdentifier= -observe.common.healthness= -observe.common.homeId= -observe.common.hookPosition= -observe.common.hookSize= -observe.common.hookType= -observe.common.hooksComposition= -observe.common.id= -observe.common.inconnu=Desconocido -observe.common.itemHorizontalPosition= -observe.common.itemVerticalPosition= -observe.common.lengthWeightFormula=Relación de peso -observe.common.lengthWeightParameter= -observe.common.lightsticksColor= -observe.common.lightsticksType= -observe.common.lineType= -observe.common.locode=Locode -observe.common.maturityStatus= -observe.common.meanWeight=Peso medio (en Kg) -observe.common.mitigationType= -observe.common.name=Name -observe.common.nocode=No code -observe.common.nonTargetCatch=Fauna asociada conservada o descartada -observe.common.nonTargetLength= -observe.common.nonTargetSample=Muestreo fauna asociada -observe.common.none=No especificada -observe.common.objectFate=Devenir de objeto -observe.common.objectObservedSpecies= -observe.common.objectOperation=Operación sobre la baliza -observe.common.objectSchoolEstimate= -observe.common.objectType=Tipo de objeto -observe.common.observedSystem=Sistema observado -observe.common.observerLabel=Observador -observe.common.ocean=Océano -observe.common.ocean/label1=Océano -observe.common.ocean/label2=Océano -observe.common.ocean/label3=Océano -observe.common.ocean/label4=Océano -observe.common.ocean/label5=Océano -observe.common.ocean/label6=Océano -observe.common.ocean/label7=Océano -observe.common.ocean/label8=Océano -observe.common.oldCode3L=Antiguo código\: -observe.common.organism=Organismo -observe.common.person=Observador -observe.common.program=Programa -observe.common.reasonForDiscard=Razon de descarte -observe.common.reasonForNoFishing=Razón de no lance de Cerco -observe.common.reasonForNullSet=Causa de lance nulo -observe.common.route=Ruta -observe.common.schoolEstimate=Estimación del banco -observe.common.scientificLabel= -observe.common.section= -observe.common.sensorBrand= -observe.common.sensorDataFormat= -observe.common.sensorPosition= -observe.common.sensorType= -observe.common.sensorUsed= -observe.common.setLongline=Lance -observe.common.setSeine=Lance -observe.common.settingIdentifier= -observe.common.settingShape= -observe.common.sex=Sexo -observe.common.sizeMeasure= -observe.common.sizeMeasureType= -observe.common.species=Especie -observe.common.species/scientificLabel=Especie -observe.common.speciesFate=Devenir de fauna -observe.common.speciesGroup=Grupo de especie de fauna -observe.common.speciesList= -observe.common.speciesStatus=Estado de especie -observe.common.stomacFullness= -observe.common.surroundingActivity=Actividad circundante -observe.common.targetCatch=Captura de atún -observe.common.targetLength=Talla de Atún -observe.common.targetSample=Muestreo atún descartado -observe.common.tdr= -observe.common.tdrRecord= -observe.common.time= -observe.common.totalCount=Número estimado -observe.common.tracelineLength= -observe.common.transmittingBuoy=Lectura de baliza -observe.common.transmittingBuoyOperation= -observe.common.transmittingBuoyType= -observe.common.tripLongline=Marea -observe.common.tripSeine=Marea -observe.common.tripType= -observe.common.vessel=Barco -observe.common.vessel/label1=Barco -observe.common.vessel/label2=Barco -observe.common.vessel/label3=Barco -observe.common.vessel/label4=Barco -observe.common.vessel/label5=Barco -observe.common.vessel/label6=Barco -observe.common.vessel/label7=Barco -observe.common.vessel/label8=Barco -observe.common.vesselActivityLongline= -observe.common.vesselActivitySeine= -observe.common.vesselActivitySeine/label1= -observe.common.vesselActivitySeine/label2= -observe.common.vesselActivitySeine/label3= -observe.common.vesselActivitySeine/label4= -observe.common.vesselActivitySeine/label5= -observe.common.vesselActivitySeine/label6= -observe.common.vesselActivitySeine/label7= -observe.common.vesselActivitySeine/label8= -observe.common.vesselSizeCategory=Capacidad -observe.common.vesselType=Pesquería -observe.common.weightCategory=Categoría de peso -observe.common.weightMeasure= -observe.common.weightMeasureType= -observe.common.wind=Fuerza del viento -observe.message.consolidate.computed.taille=Talla calculada \: %1$s (peso\:%2$s, relación talla\: %3$s, coeficientes\: %4$s) -observe.message.consolidate.computed.weight=Peso calculado \: %1$s (talla\:%2$s, relación peso\: %3$s, coeficientes\: %4$s) -observe.message.consolidate.maree.need.update=La marea %1$s se actualizará después de los cálculos. -observe.message.consolidate.no.activity.from.maree=Ninguna actividad para la marea %1$s -observe.message.consolidate.no.parametrage.found=No se encuentran ajustes para %1$s \: %2$s -observe.message.consolidate.nothing.to.save.for.maree=Nada que guardar para la marea %1$s -observe.message.consolidate.start.activity=Comenzar los cálculos de la actividad %1$s -observe.message.consolidate.start.maree=Comenzar los cálculos para la marea %1$s -observe.service.build.synchro.referentiel=Creación del referencial para el/la %1$s -observe.storage.connexionStatut.failed=Error en la conexión -observe.storage.connexionStatut.failed.description=El error en la conexión se ha debido a las siguientes razones \:\n %1$s -observe.storage.connexionStatut.success=Conexión realizada con éxito -observe.storage.connexionStatut.success.description=Información sobre la conexión \:\n%1$s. -observe.storage.connexionStatut.untested=Conexión no válida -observe.storage.connexionStatut.untested.description=La conexión no se ha validado, \n o ha sido modificada después de la última prueba de conexión. -observe.storage.creationMode.empty=Generar una base vacía -observe.storage.creationMode.empty.description=Generar una nueva base local vacía.\n Esta base no tendrá referenciales y a continuación deberá realizar la importación del referencial... -observe.storage.creationMode.externalDump=Cargar una copia de seguridad local (*.sql.gz) -observe.storage.creationMode.externalDump.description=Crear una nueva base local a partir de \n una copia de seguridad previa. -observe.storage.creationMode.importLocalStorage=Importar el referencial de una base local -observe.storage.creationMode.importLocalStorage.description=Generar una nueva base local e importar el referencial de otra base local. -observe.storage.creationMode.importRemoteStorage=Importar el referencial de una base remota -observe.storage.creationMode.importRemoteStorage.description=Generar una nueva base local e importar el referencial de una base remota. -observe.storage.creationMode.internalDump=Cargar la base -observe.storage.creationMode.internalDump.description=Generar nueva base lcoal a partir de la última versión de la base embarcada. -observe.storage.dataPolicy.data=Datos de observador -observe.storage.dataPolicy.no.wrights=Ningún permiso -observe.storage.dataPolicy.read=Lectura -observe.storage.dataPolicy.readData=Lectura de datos de observador -observe.storage.dataPolicy.readData.description=Autorización para leer datos de los observadores -observe.storage.dataPolicy.readReferentiel=Lectura del referencial -observe.storage.dataPolicy.readReferentiel.description=Autorización para leer los datos del referencial -observe.storage.dataPolicy.readWrite=Lectura / Escritura -observe.storage.dataPolicy.referentiel=Referencial -observe.storage.dataPolicy.write=Escritura -observe.storage.dataPolicy.writeData=Eacritura de datos del observador -observe.storage.dataPolicy.writeData.description=Autorización de escritura de datos de los observadores -observe.storage.dataPolicy.writeReferentiel=Escritura del referencial -observe.storage.dataPolicy.writeReferentiel.description=Autorización de escritura de datos en los referenciales -observe.storage.database.higher.than.application=You databse is in higher version (%s). ObServe version (%s) can not open it. Please get the last version of the software. -observe.storage.db.version=Versión \: -observe.storage.dbMode.createLocal=Crear una base local -observe.storage.dbMode.createLocal.description=Crear una base local de tipo h2 -observe.storage.dbMode.useLocal=Utilizar una base local -observe.storage.dbMode.useLocal.description=Utilizar una base local de tipo h2 -observe.storage.dbMode.useRemote=Utilizar una base remota -observe.storage.dbMode.useRemote.description=Utilizar una base remota de tipo postgres -observe.storage.error.import.referentiel=Ha ocurrido un errror durante la importación del referencial \: %$s -observe.storage.error.newConfig=Error en la instanciación de una nueva configuración de tipo [%1$S] debido a \: %2$s -observe.storage.error.newService=Error en la instación de un nuevo servicio de tipo [%1$s] debido a \: %2$s -observe.storage.h2.login=Login -observe.storage.label.local=Base local -observe.storage.message.closed=Servicio de persistencia [%1$s] cerrado -observe.storage.message.closing=Cierre del servicio de persistencia [%1$s] -observe.storage.message.create.from.script=Creación %1$s a partir del script %2$s -observe.storage.message.create.schema=Creación del esquema dee %1$s -observe.storage.message.import.data.from= -observe.storage.message.import.data.to= -observe.storage.message.import.referentiel.done=Finalizada la operación de importación del referencial. -observe.storage.message.import.referentiel.from=Uso del servicio [%1$s] para la importación del referencial -observe.storage.message.import.referentiel.to=Importación del referencial hacia el servicio [%1$s] -observe.storage.message.launch.migration=Ejecución del servicio de migración %1$s -observe.storage.message.opened=Servicio de persistencia [%1$s] abierto. -observe.storage.message.opening=Apertura del servicio de persistencia [%1$s] -observe.storage.message.provider.detected=Servicio de persistencia detectado [%1$s] -observe.storage.message.replicate.data.entity=Replicación de objetos '%1$s' hacia <%2$s> -observe.storage.message.replicate.data.no.data=Ningún dato a replicar -observe.storage.message.replicate.entities.done=Finalizada la replicación de datos en %1$s -observe.storage.message.replicate.entities.starting=Ejecución de la replicación de datos (%1$td/%1$tm/%1$tY à %1$tH\:%1$tM\:%1$tS) -observe.storage.message.replicate.referentiel.done=La replicación del referencia se ha realizado con éxito en %1$s -observe.storage.message.replicate.referentiel.starting=Ejecución de la replicación del referencial (%1$td/%1$tm/%1$tY à %1$tH\:%1$tM\:%1$tS) -observe.storage.message.storeDB=Copia de seguridad de la base local en el archivo %1$s -observe.storage.remote.isUsingSll=uso del modo ssl -observe.storage.remote.login=Login -observe.storage.remote.url=Url -observe.storage.remote.wrights=Permisos -observe.storage.unversionned.db=La base no está versionada -observe.synchro.obsolete.entity.label=%1$s \: %2$s"" -observe.synchro.obsolete.entity.ref=Referencia de tipo %1$s \: %2$s (propietario %3$s) -observe.validation.model.type.all=Datos y referenciales -observe.validation.model.type.all.description=Datos y referenciales -observe.validation.model.type.data=Datos del observador -observe.validation.model.type.data.description=Datos del observador -observe.validation.model.type.referentiel=Referencial -observe.validation.model.type.referentiel.description=Todos los referenciales diff --git a/observe-business/src/main/resources/i18n/observe-business_fr_FR.properties b/observe-business/src/main/resources/i18n/observe-business_fr_FR.properties deleted file mode 100644 index 6160b02..0000000 --- a/observe-business/src/main/resources/i18n/observe-business_fr_FR.properties +++ /dev/null @@ -1,234 +0,0 @@ -nuitonutil.error.convertor.noValue= -nuitonutil.error.float.convertor= -nuitonutil.error.no.convertor= -observe.common.activityLongline=Activité -observe.common.activitySeine=Activité -observe.common.baitHaulingStatus=Status de l'appât au virage -observe.common.baitSettingStatus=Status de l'appât au filage -observe.common.baitType=Type d'appât -observe.common.baitsComposition=Composition des appâts -observe.common.basket=Basket -observe.common.branchline=Avançon -observe.common.branchlineLength=Avançon (m) -observe.common.branchlinesComposition=Composition des avançons -observe.common.catchFateLongline=Devenir capture -observe.common.catchLongline=Capture -observe.common.catchWeight=Poids estimé (en t) -observe.common.country=Pays -observe.common.detectionMode=Mode détection -observe.common.encounter=Rencontre -observe.common.encounterType=Type de rencontre -observe.common.faoCode=Code FAO -observe.common.floatingObject=Objet flottant -observe.common.floatline1Length=Orin 1 (m) -observe.common.floatline2Length=Orin 2 (m) -observe.common.floatlineLengths=Template -observe.common.floatlinesComposition=Composition des orins -observe.common.fpaZone=Zone FPA -observe.common.gear=Équipement -observe.common.gearCaracteristic=Caractéristique d'un équipement -observe.common.gearCaracteristicType=Type de caractéristique d'équipement -observe.common.gearUseFeaturesLongline=Équipement -observe.common.gearUseFeaturesSeine=Équipement -observe.common.gender=Sexe -observe.common.gps.activity=Activité -observe.common.gps.gpsPoint=Point GPS -observe.common.gps.gpsPointInterval=Intervalle de points -observe.common.harbour=Port -observe.common.haulingIdentifier=Virage -observe.common.healthness=État de santé -observe.common.homeId=Identifiant -observe.common.hookPosition=Position du hameçon -observe.common.hookSize=Taille -observe.common.hookType=Type d'hameçon -observe.common.hooksComposition=Composition des hameçons -observe.common.id=Identifiant -observe.common.inconnu=inconnu -observe.common.itemHorizontalPosition=Localisation de l'élément sur la ligne mère -observe.common.itemVerticalPosition=Localisation de l'élément sur l'avançon -observe.common.lengthWeightFormula=Relation Poids -observe.common.lengthWeightParameter=Relation Taille-Poids -observe.common.lightsticksColor=Couleur de baton lumineux -observe.common.lightsticksType=Type de baton lumineux -observe.common.lineType=Type de ligne -observe.common.locode=Locode -observe.common.maturityStatus=Maturité -observe.common.meanWeight=Poids moyen (en Kg) -observe.common.mitigationType=Type de mesure d'atténuation -observe.common.name=Nom -observe.common.nocode=code absent -observe.common.nonTargetCatch=Faune accessoire conservée ou rejetée -observe.common.nonTargetLength=Longueur (cm inf.) -observe.common.nonTargetSample=Echantillon faune accessoire -observe.common.none=Aucun -observe.common.objectFate=Devenir de l'objet -observe.common.objectObservedSpecies=Faune observée -observe.common.objectOperation=Opération sur l'objet -observe.common.objectSchoolEstimate=Estimation banc objet -observe.common.objectType=Type d'objet -observe.common.observedSystem=Système observé -observe.common.observerLabel=Observateur -observe.common.ocean=Océan -observe.common.ocean/label1=Océan -observe.common.ocean/label2=Océan -observe.common.ocean/label3=Océan -observe.common.ocean/label4=Océan -observe.common.ocean/label5=Océan -observe.common.ocean/label6=Océan -observe.common.ocean/label7=Océan -observe.common.ocean/label8=Océan -observe.common.oldCode3L=ancien code \: -observe.common.organism=Organisme -observe.common.person=Personne -observe.common.program=Programme -observe.common.reasonForDiscard=Raison rejet -observe.common.reasonForNoFishing=Raison de non coup de Senne -observe.common.reasonForNullSet=Cause coup nul -observe.common.route=Route -observe.common.schoolEstimate=Estimation banc -observe.common.scientificLabel=Nom scientifique -observe.common.section=Section -observe.common.sensorBrand=Marque de capteur -observe.common.sensorDataFormat=Format de données de capteur -observe.common.sensorPosition=Position de capteur -observe.common.sensorType=Type de capteur -observe.common.sensorUsed=Capteur utilisé -observe.common.setLongline=Opération de pêche -observe.common.setSeine=Calée -observe.common.settingIdentifier=Filage -observe.common.settingShape=Forme au filage -observe.common.sex=Sexe -observe.common.sizeMeasure=Mesure de taille -observe.common.sizeMeasureType=Type de mesure de taille -observe.common.species=Espèce -observe.common.species/scientificLabel=Espèce -observe.common.speciesFate=Devenir espèce -observe.common.speciesGroup=Groupe espèce -observe.common.speciesList=Liste d'espèces -observe.common.speciesStatus=Statut faune observée -observe.common.stomacFullness=Niveau de remplissage de l'estomac -observe.common.surroundingActivity=Activité environnante -observe.common.targetCatch=Capture cible -observe.common.targetLength=Taille Thon -observe.common.targetSample=Echantillon thon rejeté -observe.common.tdr=Enregistreur de profondeur -observe.common.tdrRecord=Enregistrement de profondeur -observe.common.time=Heure -observe.common.totalCount=Nombre estimé -observe.common.tracelineLength=Partie basse (m) -observe.common.transmittingBuoy=Balise lue -observe.common.transmittingBuoyOperation=Opération balise -observe.common.transmittingBuoyType=Type de balise -observe.common.tripLongline=Marée -observe.common.tripSeine=Marée -observe.common.tripType=Type de marée -observe.common.vessel=Bateau -observe.common.vessel/label1=Bateau -observe.common.vessel/label2=Bateau -observe.common.vessel/label3=Bateau -observe.common.vessel/label4=Bateau -observe.common.vessel/label5=Bateau -observe.common.vessel/label6=Bateau -observe.common.vessel/label7=Bateau -observe.common.vessel/label8=Bateau -observe.common.vesselActivityLongline=Activité bateau -observe.common.vesselActivitySeine=Activité bateau -observe.common.vesselActivitySeine/label1=Activité bateau -observe.common.vesselActivitySeine/label2=Activité bateau -observe.common.vesselActivitySeine/label3=Activité bateau -observe.common.vesselActivitySeine/label4=Activité bateau -observe.common.vesselActivitySeine/label5=Activité bateau -observe.common.vesselActivitySeine/label6=Activité bateau -observe.common.vesselActivitySeine/label7=Activité bateau -observe.common.vesselActivitySeine/label8=Activité bateau -observe.common.vesselSizeCategory=Catégorie de bateau -observe.common.vesselType=Type de pêcherie -observe.common.weightCategory=Catégorie de poids -observe.common.weightMeasure=Mesure de poids -observe.common.weightMeasureType=Type de mesure de poids -observe.common.wind=Vent Beaufort -observe.message.consolidate.computed.taille=Taille calculée \: %1$s (weight\:%2$s, relation taille\: %3$s, coefficents\: %4$s) -observe.message.consolidate.computed.weight=Poids calculé \: %1$s (taille\:%2$s, relation poids\: %3$s, coefficents\: %4$s) -observe.message.consolidate.maree.need.update=La marée %1$s va être mise à jour suite suite aux calculs. -observe.message.consolidate.no.activity.from.maree=Aucune activité pour la marée %1$s -observe.message.consolidate.no.parametrage.found=Pas de paramétrage trouvé pour %1$s \: %2$s -observe.message.consolidate.nothing.to.save.for.maree=Rien à sauvegarder pour la marée %1$s -observe.message.consolidate.start.activity=Début des calculs pour l'activité %1$s -observe.message.consolidate.start.maree=Début des calculs pour la marée %1$s -observe.service.build.synchro.referentiel=Création du différentiel pour le référentiel %1$s -observe.storage.connexionStatut.failed=Connexion échouée -observe.storage.connexionStatut.failed.description=La connexion a échouée pour la raison suivante \:\n %1$s -observe.storage.connexionStatut.success=Connexion réussie -observe.storage.connexionStatut.success.description=Information sur la connexion \:\n%1$s. -observe.storage.connexionStatut.untested=Connexion non validée -observe.storage.connexionStatut.untested.description=La connexion n'a jamais été validée, \nou a été modifiée depuis le dernier test de connexion. -observe.storage.creationMode.empty=Générer une base vide -observe.storage.creationMode.empty.description=Générer une nouvelle base locale vide.\nCette base n'aura pas de référentiel et il vous faudra ensuite faire un import de référentiel... -observe.storage.creationMode.externalDump=Charger une sauvegarde de base locale (*.sql.gz) -observe.storage.creationMode.externalDump.description=Créer une nouvelle base locale à partir\nd'une précédente sauvegarde de l'application -observe.storage.creationMode.importLocalStorage=Importer le référentiel d'une base locale -observe.storage.creationMode.importLocalStorage.description=Générer une nouvelle base locale et y importer le référentiel d'une autre base locale. -observe.storage.creationMode.importRemoteStorage=Importer le référentiel d'une base distante -observe.storage.creationMode.importRemoteStorage.description=Générer une nouvelle base locale et y importer le référentiel d'une autre base distante. -observe.storage.creationMode.internalDump=Charger la base embarquée -observe.storage.creationMode.internalDump.description=Générer une nouvelle base locale à partir\nde la dernière version de la base embarquée. -observe.storage.dataPolicy.data=Données observateur -observe.storage.dataPolicy.no.wrights=Aucun droit. -observe.storage.dataPolicy.read=Lecture -observe.storage.dataPolicy.readData=Lecture données observateur -observe.storage.dataPolicy.readData.description=Autorisation de lire les données observateurs -observe.storage.dataPolicy.readReferentiel=Lecture référentiel -observe.storage.dataPolicy.readReferentiel.description=Autorisation de lire les données du référentiel -observe.storage.dataPolicy.readWrite=Lecture / Ecriture -observe.storage.dataPolicy.referentiel=Référentiel -observe.storage.dataPolicy.write=Ecriture -observe.storage.dataPolicy.writeData=Ecriture données observateur -observe.storage.dataPolicy.writeData.description=Autorisation d'écrire des données observateurs -observe.storage.dataPolicy.writeReferentiel=Ecriture référentiel -observe.storage.dataPolicy.writeReferentiel.description=Autorisation d'écrire des données dans le référentiel -observe.storage.database.higher.than.application=Votre base est en version supérieure (%s). Cette version d'ObServe (%s) ne peut pas l'ouvrir. Veuillez vous procuper une dernière version du logiciel. -observe.storage.db.version=Version \: -observe.storage.dbMode.createLocal=Créer une base locale -observe.storage.dbMode.createLocal.description=Creer une base locale de type h2 -observe.storage.dbMode.useLocal=Utiliser une base locale -observe.storage.dbMode.useLocal.description=Utiliser une base locale de type h2 -observe.storage.dbMode.useRemote=Utiliser une base distante -observe.storage.dbMode.useRemote.description=Utiliser une base distante de type postgres -observe.storage.error.import.referentiel=Une erreur est survenu pendant l'import du référentiel \: %$s -observe.storage.error.newConfig=L'instanciation d'une nouvelle configuration de type [%1$s] a échouée pour la raison suivante \: %2$s -observe.storage.error.newService=L'instanciation d'un nouveau service de type [%1$s] a échouée pour la raison suivante \: %2$s -observe.storage.h2.login=Login -observe.storage.label.local=Base locale -observe.storage.message.closed=Le service de persistence [%1$s] est fermé -observe.storage.message.closing=Fermeture du service de persistence [%1$s] -observe.storage.message.create.from.script=Création %1$s à partir du script %2$s -observe.storage.message.create.schema=Création du schéma de %1$s -observe.storage.message.import.data.from=Utilisation du service [%1$s] pour un import de données -observe.storage.message.import.data.to=Import de données vers le service [%1$s] -observe.storage.message.import.referentiel.done=L'opération d'import de référentiel est terminée. -observe.storage.message.import.referentiel.from=Utilisation du service [%1$s] pour un import de référentiel -observe.storage.message.import.referentiel.to=Import du référentiel vers le service [%1$s] -observe.storage.message.launch.migration=Lancement du service de migration sur %1$s -observe.storage.message.opened=Le service de persistence [%1$s] est ouvert -observe.storage.message.opening=Ouverture du service de persistence [%1$s] -observe.storage.message.provider.detected=Service de persistance détecté [%1$s] -observe.storage.message.replicate.data.entity=Réplication des objets '%1$s' vers <%2$s> -observe.storage.message.replicate.data.no.data=Aucune donnée à repliquer -observe.storage.message.replicate.entities.done=Réplication des données terminée en %1$s -observe.storage.message.replicate.entities.starting=Démarrage de la réplication de données (%1$td/%1$tm/%1$tY à %1$tT) -observe.storage.message.replicate.referentiel.done=La réplication du référentiel a été réalisée avec succès en %1$s -observe.storage.message.replicate.referentiel.starting=Démarrage de la réplication du référentiel (%1$td/%1$tm/%1$tY à %1$tT) -observe.storage.message.storeDB=Sauvegarde de la base locale dans le fichier %1$s -observe.storage.remote.isUsingSll=utilisation du mode ssl -observe.storage.remote.login=Login -observe.storage.remote.url=Url de connexion -observe.storage.remote.wrights=Droits -observe.storage.unversionned.db=La base n'est pas versionnée -observe.synchro.obsolete.entity.label=Référence de type %1$s \: %2$s -observe.synchro.obsolete.entity.ref=Référence de type %1$s \: %2$s (propriété %3$s) -observe.validation.model.type.all=Données et référentiels -observe.validation.model.type.all.description=Données et référentiels -observe.validation.model.type.data=Données observées -observe.validation.model.type.data.description=Données observées -observe.validation.model.type.referentiel=Référentiel -observe.validation.model.type.referentiel.description=Tous les référentiels diff --git a/observe-business/src/main/resources/observe-ehcache.xml b/observe-business/src/main/resources/observe-ehcache.xml deleted file mode 100644 index eee86ab..0000000 --- a/observe-business/src/main/resources/observe-ehcache.xml +++ /dev/null @@ -1,49 +0,0 @@ -<!-- - #%L - ObServe :: Business - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<ehcache> - - <diskStore path="observe.tmpdir.cache"/> - - <defaultCache - maxElementsInMemory="300" - eternal="false" - timeToIdleSeconds="120" - timeToLiveSeconds="120" - overflowToDisk="true" - diskPersistent="false" - diskExpiryThreadIntervalSeconds="120" - memoryStoreEvictionPolicy="LRU"/> - - <cache name="fr.ird.observe.entities.referentiel.Bateau" - maxElementsInMemory="10" - eternal="true" - diskPersistent="true" - overflowToDisk="true"/> - - <cache name="fr.ird.observe.entities.referentiel.BateauImpl" - maxElementsInMemory="10" - eternal="true" - diskPersistent="true" - overflowToDisk="true"/> - - -</ehcache> diff --git a/observe-business/src/main/resources/xwork.xml b/observe-business/src/main/resources/xwork.xml deleted file mode 100644 index d0f485b..0000000 --- a/observe-business/src/main/resources/xwork.xml +++ /dev/null @@ -1,30 +0,0 @@ -<!-- - #%L - ObServe :: Business - %% - Copyright (C) 2008 - 2013 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!DOCTYPE xwork PUBLIC - "-//Apache Struts//XWork 2.0//EN" - "http://struts.apache.org/dtds/xwork-2.0.dtd"> - -<xwork> - - <constant name="allowStaticMethodAccess" value="true"/> - -</xwork> diff --git a/observe-business/src/test/java/fr/ird/converter/FloatConverterTest.java b/observe-business/src/test/java/fr/ird/converter/FloatConverterTest.java deleted file mode 100644 index c1876c3..0000000 --- a/observe-business/src/test/java/fr/ird/converter/FloatConverterTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * #%L - * MS-Access Importer - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2010 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.converter; - -import org.apache.commons.beanutils.ConvertUtils; -import org.apache.commons.beanutils.Converter; -import org.junit.Assert; -import org.junit.Test; -import org.nuiton.converter.ConverterUtil; - -/** - * To test the {@link FloatConverter}. - * - * @author tchemit - chemit@codelutin.com - * @since 1.3 - */ -public class FloatConverterTest { - - @Test - public void testConvert() throws Exception { - Float actual; - - Converter c = new FloatConverter(); - - actual = c.convert(Float.class, "0"); - Assert.assertEquals(0.f, actual, 2); - - actual = c.convert(Float.class, "0,2"); - Assert.assertEquals(0.2f, actual, 2); - - actual = c.convert(Float.class, "0.2"); - Assert.assertEquals(0.2f, actual, 2); - - ConvertUtils.register(c, Float.class); - - actual = ConverterUtil.convert(Float.class, "0"); - Assert.assertEquals(0.f, actual, 2); - - actual = ConverterUtil.convert(Float.class, "0,2"); - Assert.assertEquals(0.2f, actual, 2); - - actual = ConverterUtil.convert(Float.class, "0.2"); - Assert.assertEquals(0.2f, actual, 2); - - actual = (Float) ConvertUtils.convert("0", Float.class); - Assert.assertEquals(0.f, actual, 2); - - actual = (Float) ConvertUtils.convert("0.2", Float.class); - Assert.assertEquals(0.2f, actual, 2); - - actual = (Float) ConvertUtils.convert("0,2", Float.class); - Assert.assertEquals(0.2f, actual, 2); - - - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/EntityDetectorTest.java b/observe-business/src/test/java/fr/ird/observe/EntityDetectorTest.java deleted file mode 100644 index c8cecad..0000000 --- a/observe-business/src/test/java/fr/ird/observe/EntityDetectorTest.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.ActivitySeineImpl; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.SetSeineImpl; -import fr.ird.observe.entities.seine.TargetCatch; -import fr.ird.observe.entities.seine.TargetCatchImpl; -import fr.ird.observe.entities.seine.SchoolEstimate; -import fr.ird.observe.entities.seine.TripSeine; -import fr.ird.observe.entities.seine.TripSeineImpl; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.RouteImpl; -import fr.ird.observe.entities.referentiel.Country; -import fr.ird.observe.entities.referentiel.Vessel; -import fr.ird.observe.entities.referentiel.seine.WeightCategory; -import fr.ird.observe.entities.referentiel.Ocean; -import fr.ird.observe.entities.referentiel.Organism; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.referentiel.ProgramImpl; -import org.junit.Test; -import org.nuiton.topia.persistence.util.TopiaEntityRefTester; - -/** - * Test unitaitaires de la classe de detection de types et references - * d'entites. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class EntityDetectorTest extends TopiaEntityRefTester<ObserveEntityEnum> { - - private static final String ROUTE = "route"; - - private static final String COUNTRY_ID = "country"; - - private static final String ORGANISM_ID = "organism"; - - private static final String PROGRAM_ID = "program"; - - private static final String TRIP_ID = "trip"; - - private static final String OCEAN_ID = "ocean"; - - private static final String VESSEL_ID = "vessel"; - - private static final String ACTIVITY_ID = "activity"; - - private static final String SET_ID = "set"; - - private static final String SCHOOL_ESTIMATE_ID = "schoolEstimate"; - - private static final String WEIGHT_CATEGORY_ID = "weightCategory"; - - private static final String TARGET_CATCH_ID = "targetCatch"; - - @Override - protected ObserveEntityEnum[] getContracts0() { - return ObserveEntityEnum.values(); - } - - @Test - public void testDetectTypes() throws Exception { - - Program program = new ProgramImpl(); - TripSeine maree = new TripSeineImpl(); - Route route = new RouteImpl(); - ActivitySeine activitySeine = new ActivitySeineImpl(); - SetSeine setSeine = new SetSeineImpl(); - TargetCatch discarded = new TargetCatchImpl(); - - Class<?>[] expectedClasses = new Class<?>[]{ - Program.class, - TripSeine.class, - Route.class, - ActivitySeine.class, - SetSeine.class, - TargetCatch.class - }; - - maree.setProgram(program); - detectTypes(expectedClasses, program, maree, route, activitySeine, setSeine, discarded); - -// program.addTrip(maree); - maree.addRoute(route); - route.addActivitySeine(activitySeine); - activitySeine.setSetSeine(setSeine); - - detectTypes(expectedClasses, maree, discarded); -// detect(expectedClasses, program, discarded); - - setSeine.addTargetCatch(discarded); - discarded.setSetSeine(null); - - detectTypes(expectedClasses, maree); -// detect(expectedClasses, program); - - discarded.setSetSeine(setSeine); - - detectTypes(expectedClasses, maree); -// detect(expectedClasses, program); - } - - @Test - public void testDetectReferences() throws Exception { - - Program program = newEntity(ObserveEntityEnum.Program, PROGRAM_ID); - - detectReferences(program, 0, "fake"); - - Organism organism = newEntity(ObserveEntityEnum.Organism, ORGANISM_ID); - program.setOrganism(organism); - - detectReferences(program, 1, ORGANISM_ID); - nextEntry(); - assertCurrentEntry(organism, 1); - assertNextEntityRef(program, Program.PROPERTY_ORGANISM, - program, organism); - - Country country = newEntity(ObserveEntityEnum.Country, COUNTRY_ID); - - organism.setCountry(country); - - detectReferences(program, 2, ORGANISM_ID, COUNTRY_ID); - - nextEntry(); - assertCurrentEntry(country, 1); - assertNextEntityRef(organism, Organism.PROPERTY_COUNTRY, - program, organism, country); - - nextEntry(); - assertCurrentEntry(organism, 1); - assertNextEntityRef(program, Program.PROPERTY_ORGANISM, - program, organism); - - - - TripSeine maree = newEntity(ObserveEntityEnum.TripSeine, TRIP_ID); - - Route route = newEntity(ObserveEntityEnum.Route, ROUTE); - - maree.addRoute(route); - - detectReferences(maree, 1, ROUTE); - - nextEntry(); - assertCurrentEntry(route, 1); - assertNextAssociationEntityRef(maree, TripSeine.PROPERTY_ROUTE, ROUTE, maree, route); - - Ocean ocean = newEntity(ObserveEntityEnum.Ocean, OCEAN_ID); - - maree.setOcean(ocean); - - detectReferences(maree, 2, OCEAN_ID, ROUTE); - - nextEntry(); - assertCurrentEntry(ocean, 1); - assertNextEntityRef(maree, TripSeine.PROPERTY_OCEAN, - maree, ocean); - - nextEntry(); - assertCurrentEntry(route, 1); - assertNextAssociationEntityRef(maree, TripSeine.PROPERTY_ROUTE, ROUTE, - maree, route); - - - Vessel vessel = newEntity(ObserveEntityEnum.Vessel, VESSEL_ID); - maree.setVessel(vessel); - - detectReferences(maree, 3, VESSEL_ID, OCEAN_ID, ROUTE); - - nextEntry(); - assertCurrentEntry(ocean, 1); - assertNextEntityRef(maree, TripSeine.PROPERTY_OCEAN, - maree, ocean); - - nextEntry(); - assertCurrentEntry(route, 1); - assertNextAssociationEntityRef(maree, TripSeine.PROPERTY_ROUTE, ROUTE, - maree, route); - - nextEntry(); - assertCurrentEntry(vessel, 1); - assertNextEntityRef(maree, TripSeine.PROPERTY_VESSEL, - maree, vessel); - - ActivitySeine activitySeine = newEntity(ObserveEntityEnum.ActivitySeine, ACTIVITY_ID); - route.addActivitySeine(activitySeine); - - detectReferences(maree, 4, ACTIVITY_ID, VESSEL_ID, OCEAN_ID, ROUTE); - - nextEntry(); - assertCurrentEntry(activitySeine, 1); - assertNextAssociationEntityRef(route, Route.PROPERTY_ACTIVITY_SEINE, ACTIVITY_ID, - maree, route, activitySeine); - - nextEntry(); - assertCurrentEntry(ocean, 1); - assertNextEntityRef(maree, TripSeine.PROPERTY_OCEAN, - maree, ocean); - - nextEntry(); - assertCurrentEntry(route, 1); - assertNextAssociationEntityRef(maree, TripSeine.PROPERTY_ROUTE, ROUTE, - maree, route); - - nextEntry(); - assertCurrentEntry(vessel, 1); - assertNextEntityRef(maree, TripSeine.PROPERTY_VESSEL, - maree, vessel); - - SetSeine setSeine = newEntity(ObserveEntityEnum.SetSeine, SET_ID); - activitySeine.setSetSeine(setSeine); - - detectReferences(maree, 5, ACTIVITY_ID, VESSEL_ID, SET_ID, OCEAN_ID, ROUTE); - - nextEntry(); - assertCurrentEntry(activitySeine, 1); - assertNextAssociationEntityRef(route, Route.PROPERTY_ACTIVITY_SEINE, ACTIVITY_ID, - maree, route, activitySeine); - - nextEntry(); - assertCurrentEntry(ocean, 1); - assertNextEntityRef(maree, TripSeine.PROPERTY_OCEAN, - maree, ocean); - - nextEntry(); - assertCurrentEntry(route, 1); - assertNextEntityRef(maree, getAssociationRef(TripSeine.PROPERTY_ROUTE, ROUTE), - maree, route); - - nextEntry(); - assertCurrentEntry(setSeine, 1); - assertNextEntityRef(activitySeine, ActivitySeine.PROPERTY_SET_SEINE, - maree, route, activitySeine, setSeine); - - nextEntry(); - assertCurrentEntry(vessel, 1); - assertNextEntityRef(maree, TripSeine.PROPERTY_VESSEL, - maree, vessel); - - SchoolEstimate schoolEstimate = newEntity(ObserveEntityEnum.SchoolEstimate, SCHOOL_ESTIMATE_ID); - - setSeine.addSchoolEstimate(schoolEstimate); - schoolEstimate.setSetSeine(null); - - detectReferences(setSeine, 2, SET_ID, SCHOOL_ESTIMATE_ID); - - nextEntry(); - assertCurrentEntry(schoolEstimate, 1); - assertNextAssociationEntityRef(setSeine, SetSeine.PROPERTY_SCHOOL_ESTIMATE, SCHOOL_ESTIMATE_ID, - setSeine, schoolEstimate); - - nextEntry(); - assertCurrentEntry(setSeine, 1); - assertNextEntityRef(null, null, setSeine); - - // add cycle - - schoolEstimate.setSetSeine(setSeine); - - detectReferences(setSeine, 2, SET_ID, SCHOOL_ESTIMATE_ID); - - nextEntry(); - assertCurrentEntry(schoolEstimate, 1); - assertNextAssociationEntityRef(setSeine, SetSeine.PROPERTY_SCHOOL_ESTIMATE, SCHOOL_ESTIMATE_ID, - setSeine, schoolEstimate); - - nextEntry(); - assertCurrentEntry(setSeine, 2); - assertNextEntityRef(null, null, setSeine); - assertNextEntityRef(schoolEstimate, SchoolEstimate.PROPERTY_SET_SEINE, setSeine, schoolEstimate, setSeine); - - TargetCatch targetCatch = newEntity(ObserveEntityEnum.TargetCatch, TARGET_CATCH_ID); - - setSeine.addTargetCatch(targetCatch); - - - detectReferences(setSeine, 2, SET_ID, TARGET_CATCH_ID); - - nextEntry(); - assertCurrentEntry(setSeine, 3); - assertNextEntityRef(null, null, setSeine); - assertNextEntityRef(targetCatch, TargetCatch.PROPERTY_SET_SEINE, setSeine, targetCatch, setSeine); - assertNextEntityRef(schoolEstimate, SchoolEstimate.PROPERTY_SET_SEINE, setSeine, schoolEstimate, setSeine); - - nextEntry(); - assertCurrentEntry(targetCatch, 1); - assertNextEntityRef(setSeine, getAssociationRef(SetSeine.PROPERTY_TARGET_CATCH, TARGET_CATCH_ID), - setSeine, targetCatch); - - WeightCategory weightCategory = newEntity(ObserveEntityEnum.WeightCategory, WEIGHT_CATEGORY_ID); - targetCatch.setWeightCategory(weightCategory); - - detectReferences(setSeine, 3, SET_ID, TARGET_CATCH_ID, WEIGHT_CATEGORY_ID); - - nextEntry(); - assertCurrentEntry(setSeine, 3); - assertNextEntityRef(null, null, setSeine); - assertNextEntityRef(targetCatch, TargetCatch.PROPERTY_SET_SEINE, setSeine, targetCatch, setSeine); - assertNextEntityRef(schoolEstimate, SchoolEstimate.PROPERTY_SET_SEINE, setSeine, schoolEstimate, setSeine); - - nextEntry(); - assertCurrentEntry(targetCatch, 1); - assertNextAssociationEntityRef(setSeine, SetSeine.PROPERTY_TARGET_CATCH, TARGET_CATCH_ID, - setSeine, targetCatch); - - nextEntry(); - assertCurrentEntry(weightCategory, 1); - assertNextEntityRef(targetCatch, TargetCatch.PROPERTY_WEIGHT_CATEGORY, - setSeine, targetCatch, weightCategory); - - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/db/DBTestHelper.java b/observe-business/src/test/java/fr/ird/observe/db/DBTestHelper.java deleted file mode 100644 index 9c90d4f..0000000 --- a/observe-business/src/test/java/fr/ird/observe/db/DBTestHelper.java +++ /dev/null @@ -1,604 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import com.google.common.collect.Sets; -import fr.ird.observe.DataService; -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.ObserveDAOHelper; -import fr.ird.observe.ObserveEntityEnum; -import fr.ird.observe.db.impl.H2DataSource; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.db.impl.PGDataSource; -import fr.ird.observe.db.impl.PGDataSourceConfig; -import fr.ird.observe.db.util.PGInstall; -import fr.ird.observe.db.util.SecurityModel; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.util.Scripts; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.jdbc.Work; -import org.junit.Assert; -import org.junit.Assume; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaException; -import org.nuiton.version.Version; -import org.nuiton.version.Versions; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Modifier; -import java.net.URL; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -/** - * To helper with db tests. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DBTestHelper { - - /** Logger */ - private static final Log log = LogFactory.getLog(DBTestHelper.class); - - public static final Version V_LAST = Versions.valueOf(ObserveDAOHelper.getModelVersion()); - - public static boolean canUsePG; - - public static Class<?> testClass; - - public static void assertSchemaCreated(DataSource service, boolean noData) throws DataSourceException { - - // on verifie que le schema a bien ete cree - for (Class<? extends TopiaEntity> c : - ObserveDAOHelper.getContractClasses()) { - if (Modifier.isAbstract(c.getModifiers())) { - continue; - } - List<?> r = dataService.getList(service, c); - Assert.assertNotNull(r); - if (noData) { - Assert.assertEquals(0, r.size()); - } - } - } - - static DataService dataService = new DataService(); - - public static void assertReferentiel(DataSource localService, - DataSource importService, - ObserveEntityEnum... empty) - throws DataSourceException { - - try { - if (importService != null && !importService.isOpen()) { - importService.doOpen(); - } - List<ObserveEntityEnum> observeEntityEnums = - Arrays.asList(empty); - // on verifie que le referentiel existe sur la nouvelle base - for (ObserveEntityEnum constant : - Entities.REFERENCE_ENTITIES) { - Class<? extends TopiaEntity> c = constant.getContract(); - List<?> actual = dataService.getList(localService, c); - Assert.assertNotNull(actual); - if (!observeEntityEnums.contains(constant)) { - // FIXME Remove the empty reference list when all references will be filled - if (!REFERENCE_TO_FILL.contains(constant)) - // must not be empty - Assert.assertFalse("la donnee de type " + c + - " ne devrait pas etre vide...", - actual.isEmpty()); - } -// Assert.assertFalse(c.getName(), actual.isEmpty()); - if (importService != null) { - List<?> expected = dataService.getList(importService, c); - Assert.assertNotNull(expected); - Assert.assertEquals(expected.size(), actual.size()); - } - } - } finally { - if (importService != null) { - importService.doClose(false); - } - } - } - - protected static final Set<ObserveEntityEnum> REFERENCE_TO_FILL = Sets.newHashSet( - Arrays.asList(ObserveEntityEnum.FpaZone, - ObserveEntityEnum.BaitHaulingStatus, - ObserveEntityEnum.BaitSettingStatus, - ObserveEntityEnum.BaitType, - ObserveEntityEnum.CatchFateLongline, - ObserveEntityEnum.EncounterType, - ObserveEntityEnum.Healthness, - ObserveEntityEnum.HookPosition, - ObserveEntityEnum.HookSize, - ObserveEntityEnum.HookType, - ObserveEntityEnum.ItemVerticalPosition, - ObserveEntityEnum.ItemHorizontalPosition, - ObserveEntityEnum.LightsticksColor, - ObserveEntityEnum.LightsticksType, - ObserveEntityEnum.LineType, - ObserveEntityEnum.MaturityStatus, - ObserveEntityEnum.MitigationType, - ObserveEntityEnum.SensorBrand, - ObserveEntityEnum.SensorDataFormat, - ObserveEntityEnum.SensorType, - ObserveEntityEnum.SettingShape, - ObserveEntityEnum.SizeMeasureType, - ObserveEntityEnum.StomacFullness, - ObserveEntityEnum.TripType, - ObserveEntityEnum.VesselActivityLongline, - ObserveEntityEnum.WeightMeasureType - )); - - public static PGDataSourceConfig createPGConfig(String dbName, - boolean canMigrate, - boolean canConnect, - boolean isvalid) { - - PGDataSourceConfig config = DataSourceFactory.newPGConfig( - dbName, - TestHelper.TEST_REMOTE_ADMIN_LOGIN, - TestHelper.TEST_REMOTE_PASSWORD, - TestHelper.TEST_REMOTE_URL, - canMigrate - ); - - if (log.isInfoEnabled()) { - log.info("==== create remotedb config : " + config.getLabel()); - } - if (canConnect) { - Assert.assertEquals(canConnect, config.canConnect()); - Assert.assertEquals(isvalid, config.isValid()); - } - Assert.assertEquals(canMigrate, config.isCanMigrate()); - - return config; - } - - public static H2DataSource createAndOpenFromDump(File dir, - URL url, - boolean updateSchema, - boolean shouldExists, - boolean canMigrate, - boolean showProgression, - boolean showSql) throws IOException, - DataSourceException, - TopiaException { - - H2DataSourceConfig importConfig = - DataSourceFactory.newH2ConfigFromDump( - dir.getName(), - dir, - url, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD, - canMigrate - ); - - importConfig.setShowMigrationSql(showSql); - importConfig.setShowMigrationProgression(showProgression); - H2DataSource importService; - - importService = createDB(importConfig, shouldExists); - if (updateSchema) { - importService.getRootCtxt().updateSchema(); - } - return importService; - } - - private static H2DataSource createDB( - H2DataSourceConfig localConfig2, - boolean shouldExist) throws IOException, DataSourceException { - - H2DataSource dbCible = - DataSourceFactory.newService(localConfig2); - - Assert.assertFalse(dbCible.isOpen()); - Assert.assertEquals(shouldExist, localConfig2.isStorageExists()); - - dbCible.doOpen(); - Assert.assertTrue(dbCible.isOpen()); - return dbCible; - } - - public static void loadScript(DataSource service, - final String script) { - - TopiaContextImplementor tx = null; - - try { - - tx = (TopiaContextImplementor) - service.getRootCtxt().beginTransaction(); - - tx.getHibernate().doWork(new Work() { - - @Override - public void execute(Connection connection) throws SQLException { - if (log.isDebugEnabled()) { - log.debug("will execute a script..."); - } - PreparedStatement sta = - connection.prepareStatement(script); - sta.executeUpdate(); - if (log.isDebugEnabled()) { - log.debug("have execute a script..."); - } - sta.close(); - } - }); - - - tx.commitTransaction(); - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("could not execute script for reason " + - e.getMessage(), e); - } - if (tx != null) { - tx.rollbackTransaction(); - } - } finally { - if (tx != null) { - tx.closeContext(); - } - } - } - - - public static void createPGDb( - DataSource service, - Version version) - throws TopiaException, IOException { - - if (!service.isOpen()) { - throw new IllegalStateException("le service de persistance [" + - service + "] n'est pas ouvert."); - } - - String scriptName = getObstunaScript(version); - - if (log.isInfoEnabled()) { - log.info("load script : " + scriptName); - } - - StringBuilder out = new StringBuilder(); - - int nbLines = Scripts.loadScriptContent(scriptName, out); - - String script = out.toString(); - - if (log.isInfoEnabled()) { - log.info("created script : " + nbLines + " lines."); - } - if (log.isDebugEnabled()) { - log.debug("created script content \n" + script); - } - - loadScript(service, script); - } - - public static void dropPGDb(DataSource service) throws Exception { - - if (!service.isOpen()) { - throw new IllegalStateException("le service de persistance [" + - service + "] n'est pas ouvert."); - } - - PGInstall install = new PGInstallFromScript(); - - install.init((PGDataSourceConfig) service.getConfig(), createTestSecurityModel()); - - install.dropDb(); - } - - private static SecurityModel createTestSecurityModel() { - - SecurityModel model = new SecurityModel(); - model.setAdministrateur(TestHelper.TEST_REMOTE_ADMIN_LOGIN); - model.setRole(TestHelper.TEST_REMOTE_REFERENTIEL_LOGIN, SecurityModel.Role.referentiel, false); - model.setRole(TestHelper.TEST_REMOTE_UTILISATEUR_LOGIN, SecurityModel.Role.utilisateur, false); - model.setRole(Arrays.asList(TestHelper.TEST_REMOTE_TECHNICIENS_LOGIN), SecurityModel.Role.technicien); - return model; - } - - public static void reloadPGDb(DataSource service, - Version defaultDropVersion, - Version loadVersion) throws Exception { - - if (!service.isOpen()) { - service.doOpen(); - } - - Version dropVersion = getSafeDBVersion(service); - if (dropVersion == null) { - dropVersion = defaultDropVersion; - if (log.isInfoEnabled()) { - log.info("No db version find, will use the default one " + - defaultDropVersion); - } - } - - if (log.isInfoEnabled()) { - log.info("Reload PG will drop version " + dropVersion); - } - dropPGDb(service); - - if (log.isInfoEnabled()) { - log.info("will create db on version " + loadVersion); - } - createPGDb(service, loadVersion); - } - - public static boolean checkCanConnectPG( - String url, - String login, - char[] password) throws Exception { - - PGDataSourceConfig config; - - config = DataSourceFactory.newPGConfig( - "TEST-remote", - login, - password, - url, - false); - - boolean canConnect = config.canConnect(); - - if (!canConnect) { - if (log.isDebugEnabled()) { - log.debug("Could not connect to " + config, - config.getConnexionError()); - } - } - - return canConnect; - } - - - public static PGDataSource loadRemoteDbReferentiel(String name, - boolean forceReload) throws Exception { - - PGDataSourceConfig config = createPGConfig(name, false, true, true); - - Version lastVersion = V_LAST; - - TestHelper.setConfig(IObserveConfig.DB_VERSION, lastVersion.toString()); - - PGDataSource service = DataSourceFactory.newService(config); - - service.doOpen(); - - Version oldVersion = getSafeDBVersion(service); - - if (forceReload || oldVersion == null || - !lastVersion.equals(oldVersion)) { - - reloadPGDb(service, - oldVersion, - lastVersion - ); - } - - // application de la securite - applySecurity(service); - - return service; - } - - protected static Version getSafeDBVersion(DataSource service) { - Version oldVersion = null; - try { - oldVersion = service.getDbVersion(); - } catch (Exception e) { - // cela peut arriver si il n'y a rien dans la base - log.warn("Could nto obtain version for " + service.getShortLabel(), e); - } - return oldVersion; - } - - - public static H2DataSourceConfig createLocalTmpReferentiel( - String name) throws Exception { - - File dir = TestHelper.newLocalDB(name); - - URL url = Scripts.getLastReferentielBackup(); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigFromDump( - "tmp local db : " + name, - dir, - url, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD, - false - ); - - Assert.assertNotNull(config); - - H2DataSource service = DataSourceFactory.newService(config); - try { - - service.doOpen(); - - Assert.assertTrue(service.isOpen()); - //TODO Test il y a un referentiel - //TODO Test il n'y a pas de donnees - - } finally { - - service.doClose(false); - } - - return config; - } - - - public static H2DataSource createAndOpenEmptyDb( - File dir, boolean shouldExist) throws IOException, - DataSourceException { - H2DataSourceConfig config = createEmptyDb(dir, shouldExist); - - H2DataSource dbCible = createDB(config, shouldExist); - return dbCible; - } - - - private static H2DataSourceConfig createEmptyDb(File localDB, - boolean shouldExist) { - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigEmpty( - localDB.getName(), - localDB, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD); - - Assert.assertEquals(shouldExist, config.isStorageExists()); - - if (log.isInfoEnabled()) { - log.info("==== create empty db " + localDB.getName()); - } - - return config; - } - - public static void applySecurity(PGDataSource service) throws SQLException { - - - PGInstall install = new PGInstallFromScript(); - - install.init(service.getConfig(), createTestSecurityModel()); - - install.applySecurity(); - } - - public static void assertStorageVersion(DataSource service, - Version expectedVersion) throws DataSourceException { - Assert.assertNotNull(service); - Version version = service.getDbVersion(); - Assert.assertNotNull(version); - Assert.assertEquals(expectedVersion, version); - } - - public static void restoreEmptyPG(String dbName) throws Exception { - - DataSource service = null; - try { - service = loadRemoteDbReferentiel(dbName, true); - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("could not restore empty PG " + dbName, e); - } - throw e; - } finally { - if (service != null) { - service.doClose(false); - } - } - } - - public static void initDbForTest(Class<?> testClass, boolean canMigrate, boolean checkPG) throws Exception { - DBTestHelper.testClass = testClass; - TestHelper.initTest(testClass); - TestHelper.createApplicationContext(); - TestHelper.setConfig(IObserveConfig.DB_VERSION, - V_LAST.toString()); - - canUsePG = false; - - if (canMigrate) { - TestHelper.setConfig(AbstractDataSourceMigration.AUTO_MIGRATE, "true"); - } - if (!checkPG) { - return; - } - - canUsePG = checkCanConnectPG( - TestHelper.TEST_REMOTE_URL, - TestHelper.TEST_REMOTE_ADMIN_LOGIN, - TestHelper.TEST_REMOTE_PASSWORD - ); - - if (!canUsePG) { - if (log.isWarnEnabled()) { - log.warn("Could not connect to postgres, will skip the test [" + testClass + "]"); - } - } - Assume.assumeTrue(canUsePG); - } - - public static String getLastObstunaScript() { - return getObstunaScript(V_LAST); - } - - public static String getObstunaScript(Version version) { - String result = String.format( - Scripts.OBSTUNA_SCRIPT_PATTERN, - version.toString(), - "" - ); - if (log.isInfoEnabled()) { - log.info(result); - } - return result; - } - - /** - * Pour installer une base obstuna a partir d'un script. - * <p/> - * <b>Note:</b> Cet installateur n'est utilisé que dans les tests. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.7 - */ - public static class PGInstallFromScript extends PGInstall { - - public PGInstallFromScript() { - } - - @Override - public void execute() throws Exception { - - String scriptName = getLastObstunaScript(); - - URL script = getClass().getResource(scriptName); - - createDb(script); - } - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/db/DataServiceTest.java b/observe-business/src/test/java/fr/ird/observe/db/DataServiceTest.java deleted file mode 100644 index 60cd158..0000000 --- a/observe-business/src/test/java/fr/ird/observe/db/DataServiceTest.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.DataService; -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.test.TestHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.event.TopiaEntityEvent; -import org.nuiton.topia.event.TopiaEntityListener; -import org.nuiton.topia.persistence.TopiaDAO; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; - -/** - * Tests the {@link DataService}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataServiceTest { - - - /** Logger */ - private static final Log log = - LogFactory.getLog(DataServiceTest.class); - - - @BeforeClass - public static void init() throws Exception { - - TestHelper.initTest(DataServiceTest.class); - - TestHelper.createApplicationContext(); - - TestHelper.setConfig(IObserveConfig.DB_VERSION, - DBTestHelper.V_LAST.toString()); - } - - @Before - public void setUp() { - hits = 0; - } - - @After - public void tearDown() throws Exception { - DataSourceFactory.dispose(); - } - - @Test - public void testSetDataSource2() throws Exception { - - DataService service = new DataService(); - - service.addReferentielPropertyChangeListener(Program.class, new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - increment(); - } - }); - - File dir = TestHelper.newLocalDB("testSetDataSource2"); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigEmpty( - "testSetDataSource2", - dir, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD - ); - - Assert.assertNotNull(config); - - DataSource dataSource = DataSourceFactory.newService(config); - - dataSource.doOpen(); - - Assert.assertTrue(dataSource.isOpen()); - - DBTestHelper.assertSchemaCreated( - dataSource, - true - ); - - service.registerDataSource(dataSource); - -// Assert.assertTrue(service.isEnabled()); - - dataSource.getRootCtxt().addTopiaEntityListener(listener); - - Assert.assertEquals(0, hits); - - Program program; - TopiaContext tx = service.beginTransaction(dataSource, "createProgram"); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - program = dao.create(Program.PROPERTY_CODE, "1", Program.PROPERTY_LABEL1, "label1", Program.PROPERTY_LABEL2, "label2"); - - service.commitTransaction(dataSource, tx, "createProgram"); - } finally { - service.closeTransaction(dataSource, tx, "createProgram"); - } - - // un hit de creation - Assert.assertEquals(1, hits); - - tx = service.beginTransaction(dataSource, "loadProgram"); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - - program = dao.findByTopiaId(program.getTopiaId()); - - } finally { - service.closeTransaction(dataSource, tx, "loadProgram"); - } - - // pas de hit de load - Assert.assertEquals(1, hits); - - - tx = service.beginTransaction(dataSource, "updateProgram"); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - program = dao.findByTopiaId(program.getTopiaId()); - - program.setLabel3("label3"); - dao.update(program); - - service.commitTransaction(dataSource, tx, "updateProgram"); - } finally { - service.closeTransaction(dataSource, tx, "updateProgram"); - } - - // un hit de update - Assert.assertEquals(2, hits); - - tx = service.beginTransaction(dataSource, "deleteProgram"); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - - program = dao.findByTopiaId(program.getTopiaId()); - dao.delete(program); - - service.commitTransaction(dataSource, tx, "deleteProgram"); - } finally { - service.closeTransaction(dataSource, tx, "deleteProgram"); - } - - - // un hit de delete - Assert.assertEquals(3, hits); - - } - - @Test - public void testSetDataSource() throws Exception { - - DataService service = new DataService(); - - File dir = TestHelper.newLocalDB("testSetDataSource"); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigEmpty( - "testCreateH2ConfigEmpty", - dir, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD - ); - - Assert.assertNotNull(config); - - DataSource dataSource = DataSourceFactory.newService(config); - - dataSource.doOpen(); - - Assert.assertTrue(dataSource.isOpen()); - - DBTestHelper.assertSchemaCreated( - dataSource, - true - ); - - service.registerDataSource(dataSource); - -// Assert.assertTrue(service.isEnabled()); - - dataSource.getRootCtxt().addTopiaEntityListener(listener); - - Assert.assertEquals(0, hits); - Program program; - TopiaContext tx = service.beginTransaction(dataSource, "createProgram"); - tx.addTopiaEntityListener(listener); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - program = dao.create(Program.PROPERTY_CODE, "1", Program.PROPERTY_LABEL1, "label1", Program.PROPERTY_LABEL2, "label2"); - - service.commitTransaction(dataSource, tx, "createProgram"); - } finally { - service.closeTransaction(dataSource, tx, "createProgram"); - tx.removeTopiaEntityListener(listener); - } - - // un hit de creation - Assert.assertEquals(1, hits); - - tx = service.beginTransaction(dataSource, "loadProgram"); - tx.addTopiaEntityListener(listener); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - - program = dao.findByTopiaId(program.getTopiaId()); - - } finally { - service.closeTransaction(dataSource, tx, "loadProgram"); - tx.removeTopiaEntityListener(listener); - } - - // un hit de load -// Assert.assertEquals(1, hits); - Assert.assertEquals(2, hits); - - - tx = service.beginTransaction(dataSource, "updateProgram"); - tx.addTopiaEntityListener(listener); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - - program = dao.findByTopiaId(program.getTopiaId()); - - program.setLabel3("label3"); - dao.update(program); - - service.commitTransaction(dataSource, tx, "updateProgram"); - } finally { - service.closeTransaction(dataSource, tx, "updateProgram"); - tx.removeTopiaEntityListener(listener); - } - - // un hit de load + update -// Assert.assertEquals(2, hits); - Assert.assertEquals(4, hits); - - tx = service.beginTransaction(dataSource, "deleteProgram"); - tx.addTopiaEntityListener(listener); - try { - TopiaDAO<Program> dao = dataSource.getDAO(tx, Program.class); - - program = dao.findByTopiaId(program.getTopiaId()); - dao.delete(program); - - service.commitTransaction(dataSource, tx, "deleteProgram"); - } finally { - service.closeTransaction(dataSource, tx, "deleteProgram"); - tx.removeTopiaEntityListener(listener); - } - - // un hit de load + delete -// Assert.assertEquals(3, hits); - Assert.assertEquals(6, hits); - - } - - protected int hits; - - public void increment() { - hits++; - } - - final TopiaEntityListener listener = new TopiaEntityListener() { - - @Override - public void create(TopiaEntityEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getEntity().getTopiaId()); - } - increment(); - } - - @Override - public void load(TopiaEntityEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getEntity().getTopiaId()); - } - increment(); - } - - @Override - public void update(TopiaEntityEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getEntity().getTopiaId()); - } - increment(); - } - - @Override - public void delete(TopiaEntityEvent event) { - if (log.isInfoEnabled()) { - log.info(event.getEntity().getTopiaId()); - } - increment(); - } - }; -} diff --git a/observe-business/src/test/java/fr/ird/observe/db/DataSourceFactoryTest.java b/observe-business/src/test/java/fr/ird/observe/db/DataSourceFactoryTest.java deleted file mode 100644 index dea40d2..0000000 --- a/observe-business/src/test/java/fr/ird/observe/db/DataSourceFactoryTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.db.impl.H2DataSource; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.db.impl.H2DataSourceProvider; -import fr.ird.observe.db.impl.PGDataSource; -import fr.ird.observe.db.impl.PGDataSourceConfig; -import fr.ird.observe.db.impl.PGDataSourceProvider; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; - -import java.util.Set; - -/** - * Tests the {@link DataSourceFactory}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class DataSourceFactoryTest { - - @After - public void tearDown() throws Exception { - DataSourceFactory.dispose(); - } - - @Test - public void testGetProversId() { - Set<DataSourceProvider<?, ?>> proversId = DataSourceFactory.getProversId(); - - Assert.assertNotNull(proversId); - Assert.assertTrue(proversId.size() > 1); - Assert.assertTrue(proversId.contains(new H2DataSourceProvider())); - Assert.assertTrue(proversId.contains(new PGDataSourceProvider())); - } - - @Test - public void testGetProvider() { - - Class<H2DataSourceConfig> h2ConfigClass = H2DataSourceConfig.class; - Class<H2DataSource> h2ServiceClass = H2DataSource.class; - H2DataSourceProvider h2Config = (H2DataSourceProvider) - DataSourceFactory.getProvider(h2ConfigClass, h2ServiceClass); - - assertProvider(h2Config, h2ConfigClass, h2ServiceClass); - - Class<PGDataSourceConfig> pgConfigClass = PGDataSourceConfig.class; - Class<PGDataSource> pgServiceClass = PGDataSource.class; - - PGDataSourceProvider pgConfig = (PGDataSourceProvider) - DataSourceFactory.getProvider(pgConfigClass, pgServiceClass); - assertProvider(pgConfig, pgConfigClass, pgServiceClass); - } - - protected void assertProvider(DataSourceProvider<?, ?> provider, - Class<?> configClass, - Class<?> serviceClass) { - Assert.assertNotNull(provider); - Assert.assertEquals(configClass, provider.getConfigClass()); - Assert.assertEquals(serviceClass, provider.getServiceClass()); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/db/ReplicationServiceTest.java b/observe-business/src/test/java/fr/ird/observe/db/ReplicationServiceTest.java deleted file mode 100644 index 013a560..0000000 --- a/observe-business/src/test/java/fr/ird/observe/db/ReplicationServiceTest.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db; - -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.db.impl.H2DataSource; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.NonTargetCatch; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SchoolEstimate; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TargetCatch; -import fr.ird.observe.entities.seine.TargetLength; -import fr.ird.observe.entities.seine.TargetSample; -import fr.ird.observe.entities.seine.TripSeine; -import fr.ird.observe.entities.referentiel.Country; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.referentiel.Vessel; -import fr.ird.observe.entities.referentiel.seine.WeightCategory; -import fr.ird.observe.test.TestHelper; -import org.apache.commons.io.FileUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.persistence.TopiaEntity; - -import java.io.File; -import java.util.Date; - -/** - * Pour tester le service de replication {@link ReplicationService}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.2 - */ -public class ReplicationServiceTest { - - static protected Program program; - - static protected Country country; - - static protected Route route; - - static protected TripSeine maree; - - static protected ActivitySeine activitySeine; - - static protected SetSeine setSeine; - - static protected FloatingObject floatingObject; - - static protected SchoolEstimate schoolEstimate; - - static protected Species species; - - static protected Species speciesFaune; - - static protected WeightCategory weightCategory; - - static protected TargetCatch targetCatch; - - static protected NonTargetCatch nonTargetCatch; - - static protected TargetLength targetLength; - - static protected TargetSample targetSample; - - static protected Vessel vessel; - - protected static DataSourceConfig localDataConfig; - - protected DataSource localSource; - - protected DataSource dstSource; - - @BeforeClass - public static void init() throws Exception { - - DBTestHelper.initDbForTest(ReplicationServiceTest.class, false, false); - - File localDB = TestHelper.newLocalDB("local_source"); - - DataSource localSource = DBTestHelper.createAndOpenEmptyDb(new File(localDB, "src"), false); - - localDataConfig = localSource.getConfig(); - String txName = "createModel"; - TopiaContext tx = localSource.beginTransaction(txName); - try { - - program = localSource.getDAO(tx, Program.class).create(Program.PROPERTY_CODE, "9999", Program.PROPERTY_LABEL2, "program-1"); - country = localSource.getDAO(tx, Country.class).create(Country.PROPERTY_CODE, "9999", Country.PROPERTY_LABEL2, "country-1"); - vessel = localSource.getDAO(tx, Vessel.class).create(Vessel.PROPERTY_CODE, "9999", Vessel.PROPERTY_LABEL2, "vessel-1", Vessel.PROPERTY_FLAG_COUNTRY, country); - - species = localSource.getDAO(tx, Species.class).create(Species.PROPERTY_CODE, "9999"); - speciesFaune = localSource.getDAO(tx, Species.class).create(Species.PROPERTY_CODE, "9999"); - weightCategory = localSource.getDAO(tx, WeightCategory.class).create(WeightCategory.PROPERTY_CODE, "9999", WeightCategory.PROPERTY_SPECIES, species); - - targetSample = localSource.getDAO(tx, TargetSample.class).create(TargetSample.PROPERTY_NATURE, "nature"); - targetLength = localSource.getDAO(tx, TargetLength.class).create(TargetLength.PROPERTY_TARGET_SAMPLE, targetSample, TargetLength.PROPERTY_SPECIES, species, TargetLength.PROPERTY_COUNT, 1, TargetLength.PROPERTY_LENGTH, 1.0f); - maree = localSource.getDAO(tx, TripSeine.class).create(TripSeine.PROPERTY_START_DATE, new Date()); - route = localSource.getDAO(tx, Route.class).create(Route.PROPERTY_DATE, new Date()); - activitySeine = localSource.getDAO(tx, ActivitySeine.class).create(ActivitySeine.PROPERTY_TIME, new Date()); - setSeine = localSource.getDAO(tx, SetSeine.class).create(SetSeine.PROPERTY_START_TIME, new Date()); - floatingObject = localSource.getDAO(tx, FloatingObject.class).create(FloatingObject.PROPERTY_SUPPORT_VESSEL_NAME, "supportVesselName"); - targetCatch = localSource.getDAO(tx, TargetCatch.class).create( - TargetCatch.PROPERTY_SET_SEINE, setSeine, - TargetCatch.PROPERTY_WEIGHT_CATEGORY, weightCategory, - TargetCatch.PROPERTY_CATCH_WEIGHT, 1.0f); - -// estimation = localSource.getDAO(tx, SchoolEstimate.class).create( -// SchoolEstimate.PROPERTY_WEIGHT, 10, -// SchoolEstimate.PROPERTY_SET, set, -// SchoolEstimate.PROPERTY_SPECIES, species); - - nonTargetCatch = localSource.getDAO(tx, NonTargetCatch.class).create( - NonTargetCatch.PROPERTY_SPECIES, speciesFaune - ); - - maree.setProgram(program); - maree.addRoute(route); - route.addActivitySeine(activitySeine); - activitySeine.addFloatingObject(floatingObject); - activitySeine.setSetSeine(setSeine); - targetSample.addTargetLength(targetLength); - setSeine.addTargetSample(targetSample); - setSeine.addNonTargetCatch(nonTargetCatch); - - localSource.commitTransaction(tx, txName); - } finally { -// localSource.closeTransaction(tx, txName); - localSource.doClose(false); - } - } - - @Rule - public TestName methodName = new TestName(); - - @After - public void tearDown() throws DataSourceException { - localSource = null; - DataSourceFactory.dispose(); - } - - @Before - public void setUp() throws Exception { - - File localDB = TestHelper.newLocalDB("local_source"); - - localSource = DataSourceFactory.newService(localDataConfig, H2DataSource.class); - localSource.doOpen(); -// localSource = DBTestHelper.createAndOpenEmptyDb(new File(localDB, "src"), false); - - - File dst = new File(localDB, "dst-" + methodName.getMethodName()); - FileUtils.deleteDirectory(dst); - dstSource = DBTestHelper.createAndOpenEmptyDb(dst, false); - -// String txName = "createModel"; -// TopiaContext tx = localSource.beginTransaction(txName); -// try { -// -// program = localSource.getDAO(tx, Program.class).create(Program.PROPERTY_CODE, 9999, Program.PROPERTY_LABEL2, "program-1"); -// country = localSource.getDAO(tx, Pays.class).create(Pays.PROPERTY_CODE, 9999, Pays.PROPERTY_LABEL2, "country-1"); -// vessel = localSource.getDAO(tx, Vessel.class).create(Vessel.PROPERTY_CODE, 9999, Vessel.PROPERTY_LABEL2, "vessel-1", Bateau.PROPERTY_FLAG_COUNTRY, country); -// -// species = localSource.getDAO(tx, Species.class).create(Species.PROPERTY_CODE, 9999); -// speciesFaune = localSource.getDAO(tx, Species.class).create(Species.PROPERTY_CODE, 9999); -// weightCategory = localSource.getDAO(tx, WeightCategory.class).create(WeightCategory.PROPERTY_CODE, 9999, WeightCategory.PROPERTY_SPECIES, species); -// -// echantillon = localSource.getDAO(tx, TargetSample.class).create(TargetSample.PROPERTY_NATURE, "nature"); -// taille = localSource.getDAO(tx, TargetLength.class).create(TargetLength.PROPERTY_TARGET_SAMPLE, echantillon, TargetLength.PROPERTY_SPECIES, species, TailleThon.PROPERTY_COUNT, 1, TailleThon.PROPERTY_LENGTH, 1.0f); -// maree = localSource.getDAO(tx, Trip.class).create(Trip.PROPERTY_START_DATE, new Date()); -// route = localSource.getDAO(tx, Route.class).create(Route.PROPERTY_DATE, new Date()); -// activity = localSource.getDAO(tx, Activity.class).create(Activity.PROPERTY_TIME, new Date()); -// set = localSource.getDAO(tx, Set.class).create(Set.PROPERTY_START_TIME, new Date()); -// dcp = localSource.getDAO(tx, FloatingObject.class).create(FloatingObject.PROPERTY_SUPPORT_VESSEL_NAME, "supportVesselName"); -// discarded = localSource.getDAO(tx, TargetCatch.class).create( -// TargetCatch.PROPERTY_SET, set, -// TargetCatch.PROPERTY_WEIGHT_CATEGORY, weightCategory, -// TargetCatch.PROPERTY_WEIGHT, 1.0f); -// -//// estimation = localSource.getDAO(tx, SchoolEstimate.class).create( -//// SchoolEstimate.PROPERTY_WEIGHT, 10, -//// SchoolEstimate.PROPERTY_SET, set, -//// SchoolEstimate.PROPERTY_SPECIES, species); -// -// nonTargetCatch = localSource.getDAO(tx, NonTargetCatch.class).create( -// NonTargetCatch.PROPERTY_SPECIES, speciesFaune -// ); -// -// maree.setProgram(program); -// maree.addRoute(route); -// route.addActivitySeine(activity); -// activity.addFloatingObject(dcp); -// activity.setSet(set); -// echantillon.addTargetLength(taille); -// set.addTargetSample(echantillon); -// set.addNonTargetCatch(nonTargetCatch); -// -// localSource.commitTransaction(tx, txName); -// } finally { -// localSource.closeTransaction(tx, txName); -// -// } - - } - - @Test - public void replicateReferentiel() throws Exception { - - ReplicationService service = ObserveServiceHelper.newReplicationService(); - - service.replicateReferentiel(localSource, dstSource); - - assertEntityExistAndEquals(dstSource, - program, - country, - vessel, - species, - speciesFaune, - weightCategory - ); - } - - protected void assertEntityExistAndEquals(DataSource source, TopiaEntity... entities) throws DataSourceException, TopiaException { - TopiaContext tx = source.beginTransaction("assertEntityExistAndEquals"); - try { - for (TopiaEntity e : entities) { - - Object e2 = source.findByTopiaId(tx, e.getTopiaId()); - Assert.assertEquals(e, e2); - } - } finally { - source.closeTransaction(tx, "assertEntityExistAndEquals"); - } - - } - - @Test - public void replicateData() throws Exception { - ReplicationService service = ObserveServiceHelper.newReplicationService(); - - service.replicateReferentiel(localSource, dstSource); - - service.replicateData(localSource, dstSource, maree.getTopiaId()); - - String txName = "checkdata"; - TopiaContext tx = dstSource.beginTransaction(txName); - - try { - SetSeine setSeine2 = (SetSeine) tx.findByTopiaId(setSeine.getTopiaId()); - Assert.assertNotNull(setSeine2); - Assert.assertFalse(setSeine2.isNonTargetCatchEmpty()); - Assert.assertNotNull(setSeine2.getNonTargetCatch()); - Assert.assertEquals(1, setSeine2.sizeNonTargetCatch()); - NonTargetCatch nonTargetCatch1 = setSeine2.getNonTargetCatch().iterator().next(); - Assert.assertEquals(nonTargetCatch.getTopiaId(), nonTargetCatch1.getTopiaId()); - - Assert.assertNotNull(setSeine2.getTargetSample()); - Assert.assertEquals(1, setSeine2.sizeTargetSample()); - TargetSample ec1 = setSeine2.getTargetSample().iterator().next(); - Assert.assertEquals(targetSample.getTopiaId(), ec1.getTopiaId()); - - } finally { - dstSource.closeTransaction(tx, txName); - } - - } -} - diff --git a/observe-business/src/test/java/fr/ird/observe/db/impl/H2DataSourceConfigTest.java b/observe-business/src/test/java/fr/ird/observe/db/impl/H2DataSourceConfigTest.java deleted file mode 100644 index de22265..0000000 --- a/observe-business/src/test/java/fr/ird/observe/db/impl/H2DataSourceConfigTest.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.util.Scripts; -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.db.constants.CreationMode; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.i18n.I18n; -import org.nuiton.version.Version; - -import java.io.File; -import java.net.URL; -import java.util.Locale; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class H2DataSourceConfigTest { - - /** Logger */ - private static final Log log = - LogFactory.getLog(H2DataSourceConfigTest.class); - - static protected URL TEST_DUMP_URL; - - H2DataSourceConfig config; - - @BeforeClass - public static void beforeClass() { - TestHelper.initTest(H2DataSourceConfigTest.class); - - I18n.setDefaultLocale(Locale.FRENCH); - - Version lastVersion = DBTestHelper.V_LAST; - - TEST_DUMP_URL = Scripts.getBackupScriptURL(lastVersion, Scripts.FULL_SCRIPT); - } - - @Before - public void setup() { - if (log.isDebugEnabled()) { - log.debug("start new test"); - } - } - - @After - public void tearDown() { - config = null; - } - - @Test(expected = NullPointerException.class) - public void testConstructorFailed() throws Exception { - config = new H2DataSourceConfig(null, null); - } - - @Test(expected = IllegalStateException.class) - public void testInitFailed() throws Exception { - config = new H2DataSourceConfig("test", null); - assertNotNull(config.getDbConfig()); - // pas de name - config.init(); - } - - @Test(expected = IllegalStateException.class) - public void testInitFailed2() throws Exception { - config = new H2DataSourceConfig("test", null); - assertNotNull(config.getDbConfig()); - config.setName("name"); - // pas de directory - config.init(); - } - - @Test(expected = IllegalStateException.class) - public void testInitFailed3() throws Exception { - config = new H2DataSourceConfig("test", null); - assertNotNull(config.getDbConfig()); - config.setName("name"); - config.setStorageDirectory(new File("fake")); - // pas de creationMode - config.init(); - } - - @Test - public void testInit() throws Exception { - config = new H2DataSourceConfig("test"); - assertNotNull(config.getDbConfig()); - config.setName("name"); - config.setStorageDirectory(new File("fake")); - config.setCreationMode(CreationMode.EMPTY); - config.setLogin("fakeLogin"); - config.setPassword("fakeLogin".toCharArray()); - config.init(); - assertFalse(config.isCanMigrate()); - } - - @Test - public void testClone() throws Exception { - H2DataSourceConfig clone; - config = new H2DataSourceConfig("test"); - - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setName("name"); - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setStorageDirectory(new File("fake")); - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setCreationMode(CreationMode.EMPTY); - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setDbDump(TEST_DUMP_URL); - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setLogin("fakeLogin"); - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setPassword("fakePassword".toCharArray()); - clone = config.clone(); - assertConfigEquals(config, clone); - - - // h2 importService - H2DataSourceConfig h2ImportConfig; - - h2ImportConfig = new H2DataSourceConfig("importH2"); - - config.setImportConfig(h2ImportConfig); - clone = config.clone(); - assertConfigEquals(config, clone); - - h2ImportConfig.setCreationMode(CreationMode.EMPTY); - clone = config.clone(); - assertConfigEquals(config, clone); - - h2ImportConfig.setName("importName"); - clone = config.clone(); - assertConfigEquals(config, clone); - - h2ImportConfig.setDbDump(TEST_DUMP_URL); - clone = config.clone(); - assertConfigEquals(config, clone); - - h2ImportConfig.setStorageDirectory(new File("importFake")); - clone = config.clone(); - assertConfigEquals(config, clone); - - h2ImportConfig.setLogin("fakeLogin"); - clone = config.clone(); - assertConfigEquals(config, clone); - - h2ImportConfig.setPassword("fakePassword".toCharArray()); - clone = config.clone(); - assertConfigEquals(config, clone); - } - - @Test - public void testIsValid() throws Exception { - - config = new H2DataSourceConfig("test", null); - - assertFalse(config.isValid()); - - - config.setName("name"); - - assertFalse(config.isValid()); - - config.setStorageDirectory(new File("fake")); - - assertFalse(config.isValid()); - - config.setCreationMode(null); - assertFalse(config.isValid()); - } - - protected static void assertConfigEquals(H2DataSourceConfig expected, H2DataSourceConfig actual) { - if (log.isDebugEnabled()) { - log.debug("expected : " + expected + " vs actual " + actual); - } - assertTrue(expected + " can not be same as " + actual, expected != actual); - assertEquals(expected.getLabel(), actual.getLabel()); - assertEquals(expected.getStorageDirectory(), actual.getStorageDirectory()); - assertEquals(expected.getName(), actual.getName()); - assertEquals(expected.getLogin(), actual.getLogin()); - assertEquals(expected.getPassword(), actual.getPassword()); - assertEquals(expected.getCreationMode(), actual.getCreationMode()); - assertEquals(expected.getDbDump(), actual.getDbDump()); - assertEquals(expected.isStorageExists(), actual.isStorageExists()); - assertEquals(expected.getDataDirectory(), actual.getDataDirectory()); -// if (expected.hasH2ImportConfig()) { -// assertConfigEquals(expected.getH2ImportConfig(), actual.getH2ImportConfig()); -// } -// if (expected.hasPGImportConfig()) { -// assertConfigEquals(expected.getPGImportConfig(), actual.getPGImportConfig()); -// } - } - - protected static void assertConfigEquals(PGDataSourceConfig expected, PGDataSourceConfig actual) { - if (log.isDebugEnabled()) { - log.debug("expected : " + expected + " vs actual " + actual); - } - assertTrue(expected != actual); - assertEquals(expected.getUrl(), actual.getUrl()); - assertEquals(expected.getLogin(), actual.getLogin()); - assertEquals(expected.getPassword(), actual.getPassword()); - assertEquals(expected.isUseSsl(), actual.isUseSsl()); -// assertEquals(expected.getSslCertificatFile(), actual.getSslCertificatFile()); - assertEquals(expected.getLabel(), actual.getLabel()); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/db/impl/PGDataSourceConfigTest.java b/observe-business/src/test/java/fr/ird/observe/db/impl/PGDataSourceConfigTest.java deleted file mode 100644 index 41ed665..0000000 --- a/observe-business/src/test/java/fr/ird/observe/db/impl/PGDataSourceConfigTest.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.impl; - -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.db.constants.CommonDataSourceConfigParam; -import fr.ird.observe.db.constants.ConnexionStatus; -import fr.ird.observe.db.constants.DataPolicy; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.EnumSet; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class PGDataSourceConfigTest { - - /** Logger */ - private static final Log log = LogFactory.getLog(PGDataSourceConfigTest.class); - - PGDataSourceConfig config; - - @BeforeClass - public static void beforeClass() { - - TestHelper.initTest(PGDataSourceConfigTest.class); - - TestHelper.createApplicationContext(); - - TestHelper.setConfig(IObserveConfig.DB_VERSION, - DBTestHelper.V_LAST.toString() - ); - } - - @After - public void tearDown() { - config = null; - } - - @Test(expected = NullPointerException.class) - public void testConstructorFailed() throws Exception { - config = new PGDataSourceConfig(null, null); - } - - @Test(expected = IllegalStateException.class) - public void testInitFailed() throws Exception { - config = new PGDataSourceConfig("test", null); - assertNotNull(config.getDbConfig()); - // pas d'url - config.init(); - } - - @Test(expected = IllegalStateException.class) - public void testInitFailed2() throws Exception { - config = new PGDataSourceConfig("test", null); - assertNotNull(config.getDbConfig()); - config.setUrl("url"); - // pas de login - config.init(); - } - - @Test(expected = IllegalStateException.class) - public void testInitFailed3() throws Exception { - config = new PGDataSourceConfig("test", null); - assertNotNull(config.getDbConfig()); - config.setUrl("url"); - config.setLogin("login"); - // pas de password - config.init(); - } - -// @Test(expected = IllegalStateException.class) -// public void testInitFailed4() throws Exception { -// config = new PGDataSourceConfig("test", null); -// assertNotNull(config.getDbConfig()); -// config.setUrl("url"); -// config.setLogin("login"); -// config.setUseSsl(true); -// // pas de fichier ssl -// config.init(); -// } -// -// @Test(expected = IllegalStateException.class) -// public void testInitFailed5() throws Exception { -// config = new PGDataSourceConfig("test", null); -// assertNotNull(config.getDbConfig()); -// config.setUrl("url"); -// config.setLogin("login"); -// config.setUseSsl(true); -// config.setSslCertificatFile(new File("fake" + System.nanoTime())); -// // fichier inexistant -// config.init(); -// } - - @Test - public void testInit() throws Exception { - config = new PGDataSourceConfig("test", null); - assertNotNull(config.getDbConfig()); - config.setUrl("url"); - config.setLogin("login"); - config.setPassword("password".toCharArray()); - config.init(); - assertFalse(config.isCanMigrate()); - } - - @Test - public void testClone() throws Exception { - PGDataSourceConfig clone; - config = new PGDataSourceConfig("test", null); - - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setUrl("url"); - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setLogin("login"); - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setPassword("password".toCharArray()); - clone = config.clone(); - assertConfigEquals(config, clone); - - config.setUseSsl(true); - clone = config.clone(); - assertConfigEquals(config, clone); - -// config.setSslCertificatFile(new File("fake")); - clone = config.clone(); - assertConfigEquals(config, clone); - } - - @Test - public void testIsValid() throws Exception { - - config = new PGDataSourceConfig("test", null); - - assertFalse(config.isValid()); - assertNull(config.getConnexionError()); - - config.setUrl("url"); - - config.canConnect(); - assertFalse(config.isValid()); - assertNotNull(config.getConnexionError()); - - config.setLogin("login"); - config.canConnect(); - assertFalse(config.isValid()); - assertNotNull(config.getConnexionError()); - - config.setPassword("password".toCharArray()); - config.canConnect(); - assertFalse(config.isValid()); - assertNotNull(config.getConnexionError()); - - config.connexionStatus = ConnexionStatus.SUCCESS; - assertTrue(config.isValid()); - assertNotNull(config.getConnexionError()); - config.canConnect(); - assertFalse(config.isValid()); - assertNotNull(config.getConnexionError()); - } - - @Test - public void testCanConnect() { - - config = DataSourceFactory.newPGConfig( - "testCanConnect", - TestHelper.TEST_REMOTE_UTILISATEUR_LOGIN, - TestHelper.TEST_REMOTE_PASSWORD, - TestHelper.TEST_REMOTE_URL, - false - ); - - assertFalse(config.isCanMigrate()); - - boolean canConnect = config.canConnect(); - - if (!canConnect) { - // pas possible de se connecter au service distant - if (log.isWarnEnabled()) { - log.warn("could not connect to " + config + " for reason " + config.getConnexionError().getMessage()); - log.warn("test 'testCanConnect' is skipped..."); - } - return; - } - if (log.isInfoEnabled()) { - log.info("Connected to " + config.getUrl()); - } - - EnumSet<DataPolicy> policy = config.getPolicy(); - - // chemit 20100712 : On retire ces tests car la base peut-être a un moment - // donnee inconsistante, et cela n'est pas le but de ce but - - // l'utilisateur de base obstuna doit avoir uniquement des droits en - // lecture -// assertTrue(policy.contains(DataPolicy.READ_DATA)); -// assertTrue(policy.contains(DataPolicy.READ_REFERENTIEL)); -// assertFalse(policy.contains(DataPolicy.WRITE_DATA)); -// assertFalse(policy.contains(DataPolicy.WRITE_REFERENTIEL)); - - config = DataSourceFactory.newPGConfig( - TestHelper.TEST_REMOTE_URL, - PGDataSourceConfigParam.URL, TestHelper.TEST_REMOTE_URL, - CommonDataSourceConfigParam.LOGIN, TestHelper.TEST_REMOTE_ADMIN_LOGIN, - CommonDataSourceConfigParam.PASSWORD, TestHelper.TEST_REMOTE_PASSWORD); - - canConnect = config.canConnect(); - - if (!canConnect) { - // pas possible de se connecter au service distant - if (log.isWarnEnabled()) { - log.warn("could not connect to " + config + " for reason " + config.getConnexionError().getMessage()); - log.warn("test is skiped..."); - } - return; - } - if (log.isInfoEnabled()) { - log.info("Connected to " + config.getUrl()); - } - - policy = config.getPolicy(); - - // chemit 20100712 : On retire ces tests car la base peut-être a un moment - // donnee inconsistante, et cela n'est pas le but de ce but - - // l'utilisateur de base obstuna doit avoir uniquement des droits en - // lecture -// assertTrue(policy.contains(DataPolicy.READ_DATA)); -// assertTrue(policy.contains(DataPolicy.READ_REFERENTIEL)); -// assertTrue(policy.contains(DataPolicy.WRITE_DATA)); -// assertTrue(policy.contains(DataPolicy.WRITE_REFERENTIEL)); - - } - - @Test - public void testCanConnectFailed() { - - config = DataSourceFactory.newPGConfig( - "testCanConnectFailed", - TestHelper.TEST_REMOTE_UTILISATEUR_LOGIN + System.nanoTime(), - TestHelper.TEST_REMOTE_PASSWORD, - TestHelper.TEST_REMOTE_URL, - false - ); - - boolean canConnect = config.canConnect(); - assertNotNull(canConnect); - if (log.isInfoEnabled()) { - log.info("connexion failed for " + config.getLogin() + '@' + config.getUrl() + " for reason " + config.getConnexionError().getMessage()); - } - } - - protected void assertConfigEquals(PGDataSourceConfig expected, PGDataSourceConfig actual) { - assertEquals(expected.getLabel(), actual.getLabel()); - assertEquals(expected.getUrl(), actual.getUrl()); - assertEquals(expected.getLogin(), actual.getLogin()); - assertEquals(expected.getPassword(), actual.getPassword()); - assertEquals(expected.isUseSsl(), actual.isUseSsl()); -// assertEquals(expected.getSslCertificatFile(), actual.getSslCertificatFile()); - assertEquals(expected.getConnexionStatus(), actual.getConnexionStatus()); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/gps/GPSFileReaderTest.java b/observe-business/src/test/java/fr/ird/observe/gps/GPSFileReaderTest.java deleted file mode 100644 index f0f17c4..0000000 --- a/observe-business/src/test/java/fr/ird/observe/gps/GPSFileReaderTest.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.gps; - -import org.junit.After; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.File; -import java.net.URL; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -@Ignore -public class GPSFileReaderTest { - - GPSService service = new GPSService(); - - protected GPSFileReader reader; - - @After - public void after() { - reader = null; - } - - @Test - public void testParseFile() throws Exception { - GPSRoute result = load("GL50_13_small.gpx", 10, 25.0f); - assertNotNull(result); - - assertEquals(15, result.getPoint().size()); - GPSPoint point = result.getPoint(0); - /* - <trkpt lat="-4.621102" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T03:54:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - */ - assertNotNull(point); - - assertEquals(0.0f, point.getVitesse(), 2); - assertEquals(-4.621102f, point.getLatitude(), 6); - assertEquals(55.461163f, point.getLongitude(), 6); - - } - - @Test - public void testDetectIntervals() throws Exception { - - GPSRoute route; - - // accepted = [0,13] - route = loadAndDetectInterval("testInterval_allAccepted.gpx", 10, 25.0f); - assertEquals(14, route.getPoint().size()); - assertIntervals(route, new int[]{0, 13}, null); - - // rejected = [0,13] - route = loadAndDetectInterval("testInterval_allRejected.gpx", 1, 25.0f); - assertEquals(14, route.getPoint().size()); - assertIntervals(route, null, new int[]{0, 13}); - - // rejected = [0,1] - // accepted = [1,13] - route = loadAndDetectInterval("testInterval_firtPointsRejected.gpx", 10, 25.0f); - assertEquals(14, route.getPoint().size()); - assertIntervals(route, new int[]{1, 13}, new int[]{0, 1}); - - // accepted = [0,12] - // rejected = [12,13] - route = loadAndDetectInterval("testInterval_lastPointsRejected.gpx", 10, 25.0f); - assertEquals(14, route.getPoint().size()); - assertIntervals(route, new int[]{0, 12}, new int[]{12, 13}); - - // accepted = [0,1] - // rejected = [1,2] - // accepted = [2,13] - route = loadAndDetectInterval("testInterval_insidePointsRejected.gpx", 5, 25.0f); - assertEquals(14, route.getPoint().size()); - assertIntervals(route, new int[]{0, 1, 2, 13}, new int[]{1, 2}); - - // accepted = [0,1] - // rejected = [1,2] - // accepted = [2,10] - // rejected = [10,12] - // accepted = [12,13] - route = loadAndDetectInterval("testInterval_insidePointsRejected2.gpx", 5, 25.0f); - assertEquals(14, route.getPoint().size()); - assertIntervals(route, new int[]{0, 1, 2, 10, 12, 13}, new int[]{1, 2, 10, 12}); - } - - protected void assertIntervals(GPSRoute route, int[] acceptedIntervals, int[] rejectedIntervals) { - List<GPSPointInterval> acceptedInterval = route.getAcceptedInterval(); - List<GPSPointInterval> rejectedInterval = route.getRejectedInterval(); - - if (acceptedIntervals == null) { - // pas d'intervalle accepté - assertNull(acceptedInterval); - - } else { - // des intervalles acceptés - assertNotNull(acceptedInterval); - assertFalse(acceptedInterval.isEmpty()); - int acceptedIntervalSize = acceptedIntervals.length / 2; - assertEquals(acceptedIntervalSize, acceptedInterval.size()); - for (int i = 0, j = acceptedIntervalSize; i < j; i++) { - int first = acceptedIntervals[i * 2]; - int last = acceptedIntervals[i * 2 + 1]; - GPSPointInterval interval = acceptedInterval.get(i); - - assertInterval(route, interval, first, last); - } - } - - if (rejectedIntervals == null) { - // pas d'intervalle rejeté - assertNull(rejectedInterval); - - } else { - // des intervalles rejetés - assertNotNull(rejectedInterval); - assertFalse(rejectedInterval.isEmpty()); - - int rejectedIntervalSize = rejectedIntervals.length / 2; - assertEquals(rejectedIntervalSize, rejectedInterval.size()); - for (int i = 0, j = rejectedIntervalSize; i < j; i++) { - int first = rejectedIntervals[i * 2]; - int last = rejectedIntervals[i * 2 + 1]; - GPSPointInterval interval = rejectedInterval.get(i); - - assertInterval(route, interval, first, last); - } - } - } - - protected void assertInterval(GPSRoute route, GPSPointInterval interval, int first, int last) { - assertEquals(last - first + 1, interval.getPoint().size()); - assertEquals(route.getPoint(first), interval.getFirstPoint()); - assertEquals(route.getPoint(last), interval.getLastPoint()); - } - - protected GPSRoute load(String path, int delay, float maxSpeed) throws Exception { - URL url = getClass().getResource(path); - File f = new File(url.getFile()); - reader = new GPSFileReader(service, f, delay, maxSpeed); - GPSRoute result = reader.read(); - return result; - } - - protected GPSRoute loadAndDetectInterval(String path, int delay, float maxSpeed) throws Exception { - GPSRoute route = load(path, delay, maxSpeed); - reader.detectIntervals(route); - return route; - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/gps/GPSRouteTest.java b/observe-business/src/test/java/fr/ird/observe/gps/GPSRouteTest.java deleted file mode 100644 index 8aeaaae..0000000 --- a/observe-business/src/test/java/fr/ird/observe/gps/GPSRouteTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.gps; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.File; -import java.net.URL; -import java.util.Date; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -@Ignore -public class GPSRouteTest { - - - GPSService service = new GPSService(); - - protected GPSFileReader reader; - - protected GPSRoute route; - - @Before - public void setUp() throws Exception { - route = loadAndDetectInterval("GL50_13_small.gpx", 10, 25.0f); - assertNotNull(route); - - assertEquals(15, route.getPoint().size()); - assertNotNull(route.getAcceptedInterval()); - assertEquals(1, route.getAcceptedInterval().size()); - } - - @After - public void tearDown() { - reader = null; - route = null; - } - - @Test - public void testGetBeforePointIndex() { - Date date; - int index; - GPSPointInterval intervalle = route.getAcceptedInterval(0); - - long minDate = intervalle.getDateMin(); - long maxDate = intervalle.getDateMax(); - - // la date n'est pas dans l'intervalle - date = new Date(minDate - 10); - index = route.getBeforePointIndex(intervalle, date.getTime()); - assertEquals(-1, index); - - // la date n'est pas dans l'intervalle - date = new Date(maxDate + 10); - index = route.getBeforePointIndex(intervalle, date.getTime()); - assertEquals(-1, index); - - // la date est la date de debut - date = new Date(minDate); - index = route.getBeforePointIndex(intervalle, date.getTime()); - assertEquals(0, index); - - // la date est la date de fin - date = new Date(maxDate); - index = route.getBeforePointIndex(intervalle, date.getTime()); - assertEquals(intervalle.getPoint().size() - 1, index); - - date = new Date(minDate + 10); - index = route.getBeforePointIndex(intervalle, date.getTime()); - assertEquals(0, index); - - date = new Date(intervalle.getPoint(1).getTime().getTime() - 10); - index = route.getBeforePointIndex(intervalle, date.getTime()); - assertEquals(0, index); - - date = new Date(intervalle.getPoint(1).getTime().getTime()); - index = route.getBeforePointIndex(intervalle, date.getTime()); - assertEquals(1, index); - - date = new Date(intervalle.getPoint(1).getTime().getTime() + 10); - index = route.getBeforePointIndex(intervalle, date.getTime()); - assertEquals(1, index); - } - - @Test - public void testGetPoint() throws Exception { - GPSPoint expResult, result; - Date date; - GPSPointInterval intervalle = route.getAcceptedInterval(0); - - long minDate = intervalle.getDateMin(); - long maxDate = intervalle.getDateMax(); - - - // la date n'est pas dans l'intervalle - date = new Date(minDate - 10); - expResult = null; - result = route.getPoint(date); - assertEquals(expResult, result); - - // la date n'est pas dans l'intervalle - date = new Date(maxDate + 10); - expResult = null; - result = route.getPoint(date); - assertEquals(expResult, result); - - // la date est la date de debut - date = new Date(minDate); - expResult = intervalle.getFirstPoint(); - result = route.getPoint(date); - assertEquals(expResult, result); - - // la date est la date de fin - date = new Date(maxDate); - expResult = intervalle.getLastPoint(); - result = route.getPoint(date); - assertEquals(expResult, result); - } - - //TODO Faire des tests sur des routes ou il ya des intervalles discardeds - - protected GPSRoute load(String path, int delay, float maxSpeed) throws Exception { - URL url = getClass().getResource(path); - File f = new File(url.getFile()); - reader = new GPSFileReader(service, f, delay, maxSpeed); - GPSRoute result = reader.read(); - return result; - } - - protected GPSRoute loadAndDetectInterval(String path, int delay, float maxSpeed) throws Exception { - route = load(path, delay, maxSpeed); - reader.detectIntervals(route); - return route; - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/gps/GPSServiceTest.java b/observe-business/src/test/java/fr/ird/observe/gps/GPSServiceTest.java deleted file mode 100644 index 07e1418..0000000 --- a/observe-business/src/test/java/fr/ird/observe/gps/GPSServiceTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.gps; - -import org.apache.commons.lang3.time.DateUtils; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.util.DateUtil; - -import java.util.Date; - -import static org.junit.Assert.assertEquals; - -/** - * Tests l'implantation du service {@link GPSService}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class GPSServiceTest { - - GPSService service = new GPSService(); - - GPSPoint nantes; - - GPSPoint rouen; - - @Before - public void setUp() throws Exception { - nantes = new GPSPointImpl(); - nantes.setLatitude(47.197f); - nantes.setLongitude(-1.525f); - - rouen = new GPSPointImpl(); - rouen.setLatitude(49.447f); - rouen.setLongitude(1.096f); - } - - @Test - public void testGetDistanceInKm() { - double expResult = 364.13; - double result = service.getDistanceInKm(nantes, rouen); - assertEquals(expResult, result, 0.5); - } - - @Test - public void testGetDistanceInMile() { - double expResult = 196.61; - double result = service.getDistanceInMile(nantes, rouen); - assertEquals(expResult, result, 0.5); - } - - @Test - public void testGetSpeed() { - - Date nantesTime = DateUtil.getTime(new Date(), false, false); - - nantes.setTime(nantesTime); - rouen.setTime(DateUtils.addHours(nantesTime, 1)); - - double speed = service.getSpeed(nantes, rouen); - double expResult = 196.61; - assertEquals(expResult, speed, 0.5); - - rouen.setTime(DateUtils.addHours(nantesTime, 2)); - - speed = service.getSpeed(nantes, rouen); - assertEquals(expResult/2, speed, 0.5); - } - - @Test - public void testGetDelay() { - //TODO - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/DataSourceFactoryIT.java b/observe-business/src/test/java/fr/ird/observe/its/DataSourceFactoryIT.java deleted file mode 100644 index bfecc05..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/DataSourceFactoryIT.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its; - -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.ObserveEntityEnum; -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.db.impl.H2DataSource; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.db.impl.PGDataSource; -import fr.ird.observe.db.impl.PGDataSourceConfig; -import fr.ird.observe.util.Scripts; -import fr.ird.observe.test.TestHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.net.URL; - -/** - * Tests the {@link DataSourceFactory}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class DataSourceFactoryIT { - - /** Logger */ - private static final Log log = - LogFactory.getLog(DataSourceFactoryIT.class); - - static boolean canUsePG; - - H2DataSource h2Service; - - PGDataSource pgService; - - @BeforeClass - public static void init() throws Exception { - - TestHelper.initTest(DataSourceFactoryIT.class); - - TestHelper.createApplicationContext(); - - TestHelper.setConfig(IObserveConfig.DB_VERSION, - DBTestHelper.V_LAST.toString()); - - boolean canConnect = DBTestHelper.checkCanConnectPG( - TestHelper.TEST_REMOTE_URL, - TestHelper.TEST_REMOTE_ADMIN_LOGIN, - TestHelper.TEST_REMOTE_PASSWORD - ); - - canUsePG = canConnect; - if (!canConnect) { - if (log.isWarnEnabled()) { - log.warn("Could not connect to postgres, will skip the test."); - } - return; - } - - DataSource service = DBTestHelper.loadRemoteDbReferentiel( - "reloadPGFor :: " + - DataSourceFactoryIT.class.getSimpleName(), false); - service.doClose(false); - } - - @AfterClass - public static void afterClass() throws Exception { - if (canUsePG) { - - // restore last pg empty test database - DBTestHelper.restoreEmptyPG("restoreEmptyPGFor :: " + - DataSourceFactoryIT.class.getSimpleName()); - } - } - - - @Before - public void setUp() throws Exception { - h2Service = null; - pgService = null; - } - - @After - public void tearDown() throws Exception { - DataSourceFactory.dispose(); - } - - @Test - public void testCreateH2ConfigImportLocalStorage() throws Exception { - - File dir = TestHelper.newLocalDB("testCreateH2ConfigImportLocalStorage"); - - H2DataSourceConfig importConfig; - importConfig = DBTestHelper.createLocalTmpReferentiel( - "testCreateH2ConfigImportLocalStorage_import"); - importConfig.setCreationMode(null); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigImportLocalStorage( - "testCreateH2ConfigImportLocalStorage local", - dir, - importConfig, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD, - false - ); - - h2Service = DataSourceFactory.newService(config); - h2Service.doOpen(); - - Assert.assertTrue(h2Service.isOpen()); - DBTestHelper.assertReferentiel( - h2Service, - null, - ObserveEntityEnum.Organism, - ObserveEntityEnum.LengthWeightParameter - ); - } - - @Test - public void testCreateH2ConfigEmpty() throws Exception { - - File dir = TestHelper.newLocalDB("testCreateH2ConfigEmpty"); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigEmpty( - "testCreateH2ConfigEmpty", - dir, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD - ); - - Assert.assertNotNull(config); - - h2Service = DataSourceFactory.newService(config); - h2Service.doOpen(); - - Assert.assertTrue(h2Service.isOpen()); - - DBTestHelper.assertSchemaCreated( - h2Service, - true - ); - - DBTestHelper.assertReferentiel( - h2Service, - null, - ObserveEntityEnum.values() - ); - } - - @Test - public void testCreateH2ConfigFromDump() throws Exception { - - File dir = TestHelper.newLocalDB("testCreateH2ConfigFromDump"); - - URL url = Scripts.getLastReferentielBackup(); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigFromDump( - "testCreateH2ConfigFromDump", - dir, - url, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD, - false - ); - - Assert.assertNotNull(config); - - h2Service = DataSourceFactory.newService(config); - h2Service.doOpen(); - - Assert.assertTrue(h2Service.isOpen()); - - DBTestHelper.assertSchemaCreated(h2Service, - false); - - DBTestHelper.assertReferentiel( - h2Service, - null, - ObserveEntityEnum.Organism, - ObserveEntityEnum.LengthWeightParameter - ); - } - - @Test - public void testCreateH2ConfigUseLocalStorage() throws Exception { - - File dir = TestHelper.newLocalDB("testCreateH2ConfigUseLocalStorage"); - - DBTestHelper.createLocalTmpReferentiel("testCreateH2ConfigUseLocalStorage"); - - H2DataSourceConfig config = - DataSourceFactory.newH2ConfigUseLocalStorage( - "testCreateH2ConfigUseLocalStorage", - dir, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD, - false - ); - - h2Service = DataSourceFactory.newService(config); - h2Service.doOpen(); - - Assert.assertTrue(h2Service.isOpen()); - - DBTestHelper.assertReferentiel( - h2Service, - null, - ObserveEntityEnum.Organism, - ObserveEntityEnum.LengthWeightParameter - ); - } - - @Test - public void testCreateH2ConfigImportRemoteStorage() throws Exception { - if (!canUsePG) { - if (log.isWarnEnabled()) { - log.warn("test is pass (no remote connexion accepted)..."); - } - return; - } - - File dir = TestHelper.newLocalDB("testCreateH2ConfigImportRemoteStorage"); - - PGDataSourceConfig remoteConfig = DataSourceFactory.newPGConfig( - "testCreateH2ConfigImportRemoteStorage :: remote storage", - TestHelper.TEST_REMOTE_UTILISATEUR_LOGIN, - TestHelper.TEST_REMOTE_PASSWORD, - TestHelper.TEST_REMOTE_URL, - false - ); - - remoteConfig.canConnect(); - - H2DataSourceConfig config = DataSourceFactory.newH2ConfigImportRemoteStorage( - "testCreateH2ConfigImportRemoteStorage :: local storage", - dir, - remoteConfig, - TestHelper.TEST_H2_LOGIN, - TestHelper.TEST_H2_PASSWORD, - false - ); - - h2Service = DataSourceFactory.newService(config); - h2Service.doOpen(); - - Assert.assertTrue(h2Service.isOpen()); - - DBTestHelper.assertReferentiel( - h2Service, - null, - ObserveEntityEnum.Organism, - ObserveEntityEnum.LengthWeightParameter - ); - - } - - @Test - public void testCreatePGConfig() throws Exception { - if (!canUsePG) { - if (log.isWarnEnabled()) { - log.warn("test is pass (no remote connexion accepted)..."); - } - return; - } - - PGDataSourceConfig remoteConfig = DataSourceFactory.newPGConfig( - "testCreatePGConfig", - TestHelper.TEST_REMOTE_UTILISATEUR_LOGIN, - TestHelper.TEST_REMOTE_PASSWORD, - TestHelper.TEST_REMOTE_URL, - false - ); - remoteConfig.canConnect(); - - pgService = DataSourceFactory.newService(remoteConfig); - - pgService.doOpen(); - - Assert.assertTrue(pgService.isOpen()); - - DBTestHelper.assertReferentiel( - pgService, - null//, -// ObserveEntityEnum.Organism, -// ObserveEntityEnum.LengthWeightParameter - ); - } - - @Test - public void testCreateEmptyTempStorage() throws Exception { - - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/PGInstallIT.java b/observe-business/src/test/java/fr/ird/observe/its/PGInstallIT.java deleted file mode 100644 index a2e070e..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/PGInstallIT.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its; - -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.impl.PGDataSourceConfig; -import fr.ird.observe.db.util.PGInstall; -import fr.ird.observe.db.util.SecurityModel; -import fr.ird.observe.test.TestHelper; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; - -import java.util.List; - -/** - * To test obstuna installation via java actions - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class PGInstallIT { - - /** Logger */ - private static final Log log = LogFactory.getLog(PGInstallIT.class); - - static boolean canUsePG; - - @BeforeClass - public static void init() throws Exception { - - TestHelper.initTest(PGInstallIT.class); - - TestHelper.createApplicationContext(); - - TestHelper.setConfig(IObserveConfig.DB_VERSION, - DBTestHelper.V_LAST.toString()); - - boolean canUsePG = DBTestHelper.checkCanConnectPG( - TestHelper.TEST_REMOTE_URL, - TestHelper.TEST_REMOTE_ADMIN_LOGIN, - TestHelper.TEST_REMOTE_PASSWORD - ); - - if (!canUsePG) { - if (log.isWarnEnabled()) { - log.warn("Could not connect to postgres, will skip the test."); - } - } else { - if (log.isInfoEnabled()) { - log.info("Connect to remote db with success!"); - } - } - Assume.assumeTrue(canUsePG); - } - - @AfterClass - public static void afterClass() throws Exception { - if (canUsePG) { - - // restore last pg empty test database - DBTestHelper.restoreEmptyPG("restoreEmptyPGFor :: " + - DataSourceFactoryIT.class.getSimpleName()); - } - } - - PGInstall install; - - SecurityModel securityModel; - - PGDataSourceConfig config; - - @Rule - public TestName name = new TestName(); - - @Before - public void before() throws Exception { - if (log.isInfoEnabled()) { - log.info("Start test [" + name.getMethodName() + "]"); - } - install = new DBTestHelper.PGInstallFromScript(); - securityModel = TestHelper.createTestSecurityModel(); - config = DBTestHelper.createPGConfig("obstuna-test", false, false, true); - } - - public void after() throws Exception { - if (log.isInfoEnabled()) { - log.info("End test [" + name.getMethodName() + "]"); - } - if (install != null) { - install.close(); - install = null; - } - securityModel = null; - config = null; - } - - @Test - public void dropDb() throws Exception { - - install.init(config, securityModel); - - install.dropDb(); - - List<Pair<String, String>> tables = install.getTables(); - - Assert.assertTrue("Should have no more tables, but found :" + tables, tables.isEmpty()); - } - - @Test - public void createdb() throws Exception { - - install.init(config, securityModel); - - install.execute(); - - List<Pair<String, String>> tables = install.getTables(); - - int size = Entities.ALL_ENTITIES.length + 1 + 2 + 2; - - Assert.assertEquals("Should have at least " + size + " tables, but found :" + tables.size(), size, tables.size()); - } - - @Test - public void applySecurity() throws Exception { - - install.init(config, securityModel); - - List<Pair<String, String>> tables = install.getTables(); - -// int size = DBHelper.ALL_ENTITIES.length + 1 + 2 + 2; - int size = Entities.ALL_ENTITIES.length; - - Assert.assertTrue("Should have at least " + size + " tables, but found :" + tables.size(), tables.size() >= size); - - if (log.isInfoEnabled()) { - log.info("Found " + tables.size() + " table(s) in " + config.getShortLabel()); - } - - install.applySecurity(); - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/RestoreEmptyPGIT.java b/observe-business/src/test/java/fr/ird/observe/its/RestoreEmptyPGIT.java deleted file mode 100644 index e1b1d19..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/RestoreEmptyPGIT.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its; - -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.db.DBTestHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Test d'intégration pour repositionne une base de test pg vide (avec - * uniquement un referentiel de la derniere version. - * <p/> - * Note: ce test n'est pas exécuté si pas de connexion disponible vers la base - * de test. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class RestoreEmptyPGIT { - - /** Logger */ - private static final Log log = LogFactory.getLog(RestoreEmptyPGIT.class); - - @BeforeClass - public static void init() throws Exception { - - TestHelper.initTest(RestoreEmptyPGIT.class); - - TestHelper.createApplicationContext(); - - TestHelper.setConfig(IObserveConfig.DB_VERSION, - DBTestHelper.V_LAST.toString()); - - boolean canConnect = DBTestHelper.checkCanConnectPG( - TestHelper.TEST_REMOTE_URL, - TestHelper.TEST_REMOTE_ADMIN_LOGIN, - TestHelper.TEST_REMOTE_PASSWORD - ); - - if (!canConnect) { - if (log.isWarnEnabled()) { - log.warn("Could not connect to postgres, will skip the test."); - } - } else { - if (log.isInfoEnabled()) { - log.info("Connect to remote db with success!"); - } - } - Assume.assumeTrue(canConnect); - } - - @Test - public void restorePg() throws Exception { - DBTestHelper.restoreEmptyPG("restoreEmptyPG"); - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/migration/AbstractDataSourceMigrationTest.java b/observe-business/src/test/java/fr/ird/observe/its/migration/AbstractDataSourceMigrationTest.java deleted file mode 100644 index fd96bd6..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/migration/AbstractDataSourceMigrationTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.migration; - -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.test.TestHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public abstract class AbstractDataSourceMigrationTest<C extends DataSourceConfig, S extends DataSource> extends AbstractMigrationTest<C, S> { - - @Before - public void setUp() throws Exception { - - TestHelper.createApplicationContext(); - TestHelper.setConfig(AbstractDataSourceMigration.AUTO_MIGRATE, "true"); - } - - @After - public void tearDown() throws DataSourceException { - config = null; - service = null; - DataSourceFactory.dispose(); - } - - @Test - public void testMigrateFrom0_TO_3_1() throws Exception { - - testForVersion(AbstractDataSourceMigration.V_3_0, AbstractDataSourceMigration.V_3_1); - } - - @Test - public void testMigrateFrom0_TO_3_5() throws Exception { - - testForVersion(AbstractDataSourceMigration.V_3_1, AbstractDataSourceMigration.V_3_5); - } - - @Test - public void testMigrateFrom0_TO_3_7() throws Exception { - - testForVersion(AbstractDataSourceMigration.V_3_1, AbstractDataSourceMigration.V_3_7); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/migration/AbstractMigrationTest.java b/observe-business/src/test/java/fr/ird/observe/its/migration/AbstractMigrationTest.java deleted file mode 100644 index 85d60ad..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/migration/AbstractMigrationTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.migration; - -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceConfig; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.test.TestHelper; -import org.junit.After; -import org.junit.Before; -import org.nuiton.version.Version; - -public abstract class AbstractMigrationTest<C extends DataSourceConfig, S extends DataSource> { - - protected C config; - - protected S service; - - protected abstract S initStorage(String testName, - Version referentielVersion, - boolean showProgression, - boolean showSql, - boolean canMigrate) throws Exception; - - @Before - public void setUp() throws Exception { - - TestHelper.createApplicationContext(); - TestHelper.setConfig(AbstractDataSourceMigration.AUTO_MIGRATE, "true"); - } - - @After - public void tearDown() throws DataSourceException { - config = null; - service = null; - DataSourceFactory.dispose(); - } - - protected final void testForVersion(Version v) throws Exception { - - boolean last = v.equals(DBTestHelper.V_LAST); - - // on ouvre la base avec migration possible avec affichage des requetes - // uniquement sur la dernière version - - service = openStorage("testMigrateFrom0_TO_" + v, - AbstractDataSourceMigration.V_3_1, - v, - last, - last, - true - ); - - DBTestHelper.assertStorageVersion(service, v); - - if (last) { - - // on est sur la dernière version, on peut tester que le schema - // a bien ete crée et que le référentiel n'est pas vide - - DBTestHelper.assertSchemaCreated(service, false); - - DBTestHelper.assertReferentiel(service, null); - } - } - - protected final void testForVersion(Version referentielVersion, Version v) throws Exception { - - boolean last = v.equals(DBTestHelper.V_LAST); - - // on ouvre la base avec migration possible avec affichage des requetes - // uniquement sur la dernière version - - service = openStorage("testMigrateFrom0_TO_" + v, - referentielVersion, - v, - last, - last, - true - ); - - DBTestHelper.assertStorageVersion(service, v); - - if (last) { - - // on est sur la dernière version, on peut tester que le schema - // a bien ete crée et que le référentiel n'est pas vide - - DBTestHelper.assertSchemaCreated(service, false); - - DBTestHelper.assertReferentiel(service, null); - } - } - - protected final S openStorage(String testName, - Version referentielVersion, - Version version, - boolean showProgression, - boolean showSql, - boolean canMigrate) throws Exception { - - TestHelper.setConfig(AbstractDataSourceMigration.DB_VERSION, version.toString()); - - S service = initStorage(testName, - referentielVersion, - showProgression, - showSql, - canMigrate); - - if (!service.isOpen()) { - service.doOpen(); - } - return service; - } - - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/migration/H2DataSourceMigrationIT.java b/observe-business/src/test/java/fr/ird/observe/its/migration/H2DataSourceMigrationIT.java deleted file mode 100644 index 790b3a3..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/migration/H2DataSourceMigrationIT.java +++ /dev/null @@ -1,390 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.migration; - -import com.google.common.base.Function; -import com.google.common.collect.Maps; -import fr.ird.observe.DataService; -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.impl.H2DataSource; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.referentiel.SpeciesGroup; -import fr.ird.observe.entities.referentiel.SpeciesImpl; -import fr.ird.observe.entities.referentiel.SpeciesList; -import fr.ird.observe.entities.referentiel.SpeciesListImpl; -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.util.Scripts; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.csv.Import; -import org.nuiton.csv.ValueParser; -import org.nuiton.csv.ext.AbstractImportModel; -import org.nuiton.version.Version; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.text.ParseException; -import java.util.List; -import java.util.Map; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public class H2DataSourceMigrationIT extends AbstractDataSourceMigrationTest<H2DataSourceConfig, H2DataSource> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(H2DataSourceMigrationIT.class); - - protected File localDB; - - @BeforeClass - public static void initClass() throws Exception { - - DBTestHelper.initDbForTest(H2DataSourceMigrationIT.class, true, false); - } - - @Override - protected H2DataSource initStorage(String testName, - Version referentielVersion, - boolean showProgression, - boolean showSql, - boolean canMigrate) throws Exception { - - localDB = TestHelper.newLocalDB(testName); - - String dbPath = - Scripts.getBackupScript(referentielVersion, "referentiel"); - - URL dbUrl = getClass().getResource(dbPath); - - Assert.assertNotNull("could not find resource : " + dbPath, dbUrl); - - service = DBTestHelper.createAndOpenFromDump( - localDB, - dbUrl, - false, - false, - canMigrate, - showProgression, - showSql); - - config = service.getConfig(); - - return service; - } - - @Test - public void testMigrateFrom0_TO_3_7() throws Exception { - - super.testMigrateFrom0_TO_3_7(); - - updateSpeciesList(); - - } - - private void updateSpeciesList() throws fr.ird.observe.db.DataSourceException, IOException { - String csvFilepath = "/db/3.7/LL_species_ref_list_for_Observe.csv"; - - URL dbUrl = getClass().getResource(csvFilepath); - - Assert.assertNotNull("could not find resource : " + csvFilepath, dbUrl); - - DataService dataService = ObserveServiceHelper.get().getDataService(); - - List<Species> speciesList = dataService.getList(service, Species.class); - - SpeciesImportModel importModel = new SpeciesImportModel(speciesList); - - String catchSpeciesListId = "fr.ird.observe.entities.referentiel.SpeciesList#1239832675370#0.3"; - String encounterSpeciesListId = "fr.ird.observe.entities.referentiel.SpeciesList#1239832675370#0.4"; - String depredatorSpeciesListId = "fr.ird.observe.entities.referentiel.SpeciesList#1239832675370#0.5"; - - SpeciesList catchSpeciesList = new SpeciesListImpl(); - SpeciesList encounterSpeciesList = new SpeciesListImpl(); - SpeciesList depredatorSpeciesList = new SpeciesListImpl(); - - StringBuilder sqlBuilder = new StringBuilder(); - - String deleteSql = "DELETE OBSERVE_COMMON.SPECIES_SPECIESLIST WHERE SPECIESLIST ='%s';\n"; - String insertSql = "INSERT INTO OBSERVE_COMMON.SPECIES_SPECIESLIST(SPECIES, SPECIESLIST) VALUES ('%s', '%s');\n"; - - sqlBuilder.append(String.format(deleteSql, catchSpeciesListId)); - sqlBuilder.append(String.format(deleteSql, encounterSpeciesListId)); - sqlBuilder.append(String.format(deleteSql, depredatorSpeciesListId)); - - InputStream inputStream = dbUrl.openStream(); - try { - Import<SpeciesImportModel.SpeciesRow> speciesRows = Import.newImport(importModel, inputStream); - - for (SpeciesImportModel.SpeciesRow speciesRow : speciesRows) { - - Species species = speciesRow.getSpecies(); - - String topiaId = species.getTopiaId(); - if (topiaId == null) { - - // create species - createSpecies(speciesRow); - continue; - } - - if (log.isDebugEnabled()) { - log.debug("Species: " + species); - } - - if (speciesRow.isCatchList()) { - catchSpeciesList.addSpecies(species); - sqlBuilder.append(String.format(insertSql, topiaId, catchSpeciesListId)); - } - if (speciesRow.isEncounterList()) { - encounterSpeciesList.addSpecies(species); - sqlBuilder.append(String.format(insertSql, topiaId, encounterSpeciesListId)); - } - if (speciesRow.isDepredatorList()) { - depredatorSpeciesList.addSpecies(species); - sqlBuilder.append(String.format(insertSql, topiaId, depredatorSpeciesListId)); - } - - } - } finally { - inputStream.close(); - } - - if (log.isInfoEnabled()) { - log.info("SQL:\n" + sqlBuilder); - } - } - - private void createSpecies(SpeciesImportModel.SpeciesRow speciesRow) { - Species species = speciesRow.getSpecies(); - String faoCode = species.getFaoCode(); - if (log.isInfoEnabled()) { - log.info("Create species " + faoCode); - } - } - - /** - * Created on 10/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ - public static class SpeciesImportModel extends AbstractImportModel<SpeciesImportModel.SpeciesRow> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(SpeciesImportModel.class); - - protected final Map<String, Species> speciesByFaoCode; - - protected final Map<String, Species> speciesByHomeId; - - public SpeciesImportModel(List<Species> speciess) { - super(','); - - speciesByFaoCode = Maps.uniqueIndex(speciess, new Function<Species, String>() { - @Override - public String apply(Species input) { - String result = input.getFaoCode(); - if (result == null) { - result = "" + System.nanoTime(); - } - return result; - } - }); - speciesByHomeId = Maps.uniqueIndex(speciess, new Function<Species, String>() { - @Override - public String apply(Species input) { - String result = input.getFaoCode(); - if (result == null) { - result = "" + System.nanoTime(); - } - return result; - } - }); - - newMandatoryColumn("fao_code", "species", new ValueParser<Species>() { - @Override - public Species parse(String value) throws ParseException { - Species species = speciesByFaoCode.get(value); - if (species == null) { - - // try with HomeId - - species = speciesByHomeId.get(value); - - if (species == null) { - - if (log.isDebugEnabled()) { - log.debug("Could not find species: " + value); - } - species = new SpeciesImpl(); - species.setFaoCode(value); - - } - - } - return species; - } - }); - - newMandatoryColumn("nom_francais", Species.PROPERTY_LABEL2); - newMandatoryColumn("english_name", Species.PROPERTY_LABEL1); - newMandatoryColumn("scientific_name", Species.PROPERTY_SCIENTIFIC_LABEL); - newIgnoredColumn("family"); - newIgnoredColumn("comments"); - - ValueParser<Boolean> booleanParser = new ValueParser<Boolean>() { - @Override - public Boolean parse(String value) throws ParseException { - return value.equals("1"); - } - }; - - newMandatoryColumn("atlantic_ocean", "oceanA", booleanParser); - newMandatoryColumn("indian_ocean", "oceanI", booleanParser); - - newMandatoryColumn("catch_dispay_list", "catchList", booleanParser); - newMandatoryColumn("predator_dispay_list", "depredatorList", booleanParser); - newMandatoryColumn("encounter_display_list", "encounterList", booleanParser); - - } - - @Override - public SpeciesRow newEmptyInstance() { - return new SpeciesRow(); - } - - public static class SpeciesRow { - - protected Species species; - - protected String label1; - - protected String label2; - - protected String scientificLabel; - - protected SpeciesGroup speciesGroup; - - protected boolean oceanA; - - protected boolean oceanI; - - protected boolean catchList; - - protected boolean depredatorList; - - protected boolean encounterList; - - public Species getSpecies() { - return species; - } - - public void setSpecies(Species species) { - this.species = species; - } - - public boolean isOceanA() { - return oceanA; - } - - public void setOceanA(boolean oceanA) { - this.oceanA = oceanA; - } - - public boolean isOceanI() { - return oceanI; - } - - public void setOceanI(boolean oceanI) { - this.oceanI = oceanI; - } - - public boolean isCatchList() { - return catchList; - } - - public void setCatchList(boolean catchList) { - this.catchList = catchList; - } - - public boolean isDepredatorList() { - return depredatorList; - } - - public void setDepredatorList(boolean depredatorList) { - this.depredatorList = depredatorList; - } - - public boolean isEncounterList() { - return encounterList; - } - - public void setEncounterList(boolean encounterList) { - this.encounterList = encounterList; - } - - public String getLabel1() { - return label1; - } - - public void setLabel1(String label1) { - this.label1 = label1; - } - - public String getLabel2() { - return label2; - } - - public void setLabel2(String label2) { - this.label2 = label2; - } - - public String getScientificLabel() { - return scientificLabel; - } - - public void setScientificLabel(String scientificLabel) { - this.scientificLabel = scientificLabel; - } - - public SpeciesGroup getSpeciesGroup() { - return speciesGroup; - } - - public void setSpeciesGroup(SpeciesGroup speciesGroup) { - this.speciesGroup = speciesGroup; - } - - } - - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/migration/PGDataSourceMigrationIT.java b/observe-business/src/test/java/fr/ird/observe/its/migration/PGDataSourceMigrationIT.java deleted file mode 100644 index a5a2fc8..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/migration/PGDataSourceMigrationIT.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.migration; - -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSourceFactory; -import fr.ird.observe.db.impl.PGDataSource; -import fr.ird.observe.db.impl.PGDataSourceConfig; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.nuiton.version.Version; - -public class PGDataSourceMigrationIT extends AbstractDataSourceMigrationTest<PGDataSourceConfig, PGDataSource> { - - /** Logger */ - private static final Log log = - LogFactory.getLog(PGDataSourceMigrationIT.class); - - @BeforeClass - public static void beforeClass() throws Exception { - - DBTestHelper.initDbForTest(PGDataSourceMigrationIT.class, true, true); - } - - @AfterClass - public static void afterClass() throws Exception { - - if (!DBTestHelper.canUsePG) { - return; - } - Version lastVersion = DBTestHelper.V_LAST; - - // creation base derniere version - - TestHelper.setConfig(AbstractDataSourceMigration.DB_VERSION, - lastVersion.toString()); - - String testName = "restoreLastPGBase"; - - String dbName = testName + " :: " + TestHelper.TEST_REMOTE_URL; - - PGDataSourceConfig c = - DBTestHelper.createPGConfig(dbName, false, true, true); - c.setShowMigrationProgression(false); - c.setShowMigrationSql(false); - - PGDataSource s = DataSourceFactory.newService(c); - - s.doOpen(); - - Version oldVersion = s.getDbVersion(); - - if (oldVersion == null || !oldVersion.equals(lastVersion)) { - - if (log.isInfoEnabled()) - log.info("Will regenerate pg db in version " + lastVersion); - // on regénère la base - DBTestHelper.reloadPGDb(s, oldVersion, lastVersion); - } - - // application de la securite - - DBTestHelper.applySecurity(s); - - DBTestHelper.assertStorageVersion(s, lastVersion); - } - - @Override - @Before - public void setUp() throws Exception { - - super.setUp(); - - // on regénère une base postgres en version 1.0.0 - -// service = openStorage("testMigrateFrom0_TO_1_0_0_init", -// AbstractDataSourceMigration.V_1_0_0, -// AbstractDataSourceMigration.V_1_0_0, -// false, -// false, -// false -// ); -// -// DBTestHelper.reloadPGDb(service, -// AbstractDataSourceMigration.V_1_0_0, -// AbstractDataSourceMigration.V_1_0_0 -// ); - -// DBTestHelper.assertStorageVersion(service, AbstractDataSourceMigration.V_1_0_0); - - service.doClose(false); - } - - @Override - protected PGDataSource initStorage(String testName, - Version referentielVersion, - boolean showProgression, - boolean showSql, - boolean canMigrate) throws Exception { - - if (log.isInfoEnabled()) { - log.info("==== start test " + testName); - } - - String dbName = testName + " :: " + TestHelper.TEST_REMOTE_URL; - - config = DBTestHelper.createPGConfig(dbName, canMigrate, true, true); - config.setShowMigrationProgression(showProgression); - config.setShowMigrationSql(showSql); - - service = DataSourceFactory.newService(config); - - return service; - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/migration/h2ToLast/AbstractH2MigrationToLastIT.java b/observe-business/src/test/java/fr/ird/observe/its/migration/h2ToLast/AbstractH2MigrationToLastIT.java deleted file mode 100644 index e090cc9..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/migration/h2ToLast/AbstractH2MigrationToLastIT.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.migration.h2ToLast; - -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.impl.H2DataSource; -import fr.ird.observe.db.impl.H2DataSourceConfig; -import fr.ird.observe.its.migration.AbstractMigrationTest; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.version.Version; - -import java.io.File; -import java.net.URL; - -/** - * Teste une base h2 avec migration vers la derniere version. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.0 - */ -public abstract class AbstractH2MigrationToLastIT extends AbstractMigrationTest<H2DataSourceConfig, H2DataSource> { - - /** Logger */ - private static final Log log = - LogFactory.getLog(AbstractH2MigrationToLastIT.class); - - /** Le chemin où trouver les scripts de bases. */ - public static final String DB_PATH = "src/test/db"; - - protected File localDB; - - protected File scriptPath; - - protected File basedir; - - protected abstract File getScriptPath(); - - @Override - @Before - public final void setUp() throws Exception { - - basedir = new File(TestHelper.getBasedir(), DB_PATH); - - scriptPath = getScriptPath(); - boolean exists = scriptPath.exists(); - if (!exists) { - if (log.isWarnEnabled()) { - log.warn("Could not find h2 script file " + scriptPath + ", will skip the test"); - } - } - Assume.assumeTrue(exists); - - super.setUp(); - } - - @Test - public final void testMigrateFrom0_TO_Last() throws Exception { - - testForVersion(DBTestHelper.V_LAST); - } - - @Override - protected final H2DataSource initStorage(String testName, - Version referentielVersion, - boolean showProgression, - boolean showSql, - boolean canMigrate) throws Exception { - - localDB = TestHelper.newLocalDB(testName); - - URL dbUrl = scriptPath.toURI().toURL(); - - Assert.assertNotNull("could not find resource : " + scriptPath, dbUrl); - - service = DBTestHelper.createAndOpenFromDump( - localDB, - dbUrl, - false, - false, - true, - true, - true); - - config = service.getConfig(); - - return service; - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/migration/h2ToLast/MigrationV4_0IT.java b/observe-business/src/test/java/fr/ird/observe/its/migration/h2ToLast/MigrationV4_0IT.java deleted file mode 100644 index 80253c6..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/migration/h2ToLast/MigrationV4_0IT.java +++ /dev/null @@ -1,48 +0,0 @@ -package fr.ird.observe.its.migration.h2ToLast; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.DBTestHelper; -import org.junit.BeforeClass; - -import java.io.File; - -/** - * Created on 6/23/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class MigrationV4_0IT extends AbstractH2MigrationToLastIT { - - @BeforeClass - public static void beforeClass() throws Exception { - - DBTestHelper.initDbForTest(MigrationV4_0IT.class, true, false); - } - - protected File getScriptPath() { - File scriptPath = new File(basedir, "observe_3.1.sql.gz"); - return scriptPath; - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateDataTest.java b/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateDataTest.java deleted file mode 100644 index 2ad5fe7..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateDataTest.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.replication; - -import fr.ird.observe.ObserveEntityEnum; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.NonTargetCatch; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SchoolEstimate; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TargetCatch; -import fr.ird.observe.entities.seine.TargetLength; -import fr.ird.observe.entities.seine.TargetSample; -import fr.ird.observe.entities.seine.TripSeine; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; - -/** @author Tony Chemit - chemit@codelutin.com */ -public abstract class AbstractReplicateDataTest extends AbstractReplicateTest { - - static protected ReplicationDataModel replicationDataModel = new ReplicationDataModel(); - - @Before - @Override - public final void setUp() throws Exception { - - if (getLog().isDebugEnabled()) { - getLog().debug("start test :)"); - } - - super.setUp(); - - updateModel(); - - if (getLog().isDebugEnabled()) { - getLog().debug("start test (end setup) :)"); - } - } - - protected void updateModel() throws Exception { - - replicationDataModel.update(ctxt); - } - - - @Override - protected void createModel(DataSource service) throws Exception { - - if (init) { - if (getLog().isInfoEnabled()) { - getLog().info("already done..."); - return; - } - } - TopiaContext tx = service.beginTransaction("createModel"); - try { - - replicationDataModel.createModel(service, tx); - - service.commitTransaction(tx, "createModel"); - } finally { - service.closeTransaction(tx, "createModel"); - - } - } - - @Override - protected final TopiaContext createReplicateDb(Object contract) throws Exception { - TopiaContext c = super.createReplicateDb(contract); - localService.getReplicationService().replicateReferentiel(localService, dbCible); - return c; - } - - @Override - protected TopiaEntityEnum[] getContracts() { - return Entities.DATA_ENTITIES; - } - - @Override - protected final void createModel(TopiaEntity entity) { - model = getModelBuilder().createModel( - context, - getContracts(), - false, - entity.getTopiaId() - ); - } - - @Override - protected final void prepareModel(String... ids) { - prepareModelWithComputedOrder(ids); - } - - @Test - @Override - public final void testDetectOperations() throws Exception { - Assume.assumeTrue(replicationDataModel != null); - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } -// detectOperations(dcp); -// detectOperations(estimation); -// detectOperations(set); -// detectOperations(activity); -// detectOperations(route); - detectOperations(replicationDataModel.tripSeine); -// detectOperations(program); - } - - @Test - @Override - public void testDoReplicate() throws Exception { - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } -// doReplicate(ObserveEntityEnum.FloatingObject, dcp); -// doReplicate(ObserveEntityEnum.SchoolEstimate, estimation); -// -// doReplicate(ObserveEntityEnum.Set, set); -// doReplicate(ObserveEntityEnum.Activity, activity); -// doReplicate(ObserveEntityEnum.Route, route); - doReplicateWithComputedOrder(replicationDataModel.tripSeine); - - TopiaContext tx = dstCtxt.beginTransaction(); - - try { - SetSeine setSeine2 = (SetSeine) tx.findByTopiaId(replicationDataModel.setSeine.getTopiaId()); - Assert.assertNotNull(setSeine2); - Assert.assertFalse(setSeine2.isNonTargetCatchEmpty()); - Assert.assertNotNull(setSeine2.getNonTargetCatch()); - Assert.assertEquals(1, setSeine2.sizeNonTargetCatch()); - NonTargetCatch nonTargetCatche1 = setSeine2.getNonTargetCatch().iterator().next(); - Assert.assertEquals(replicationDataModel.nonTargetCatch.getTopiaId(), nonTargetCatche1.getTopiaId()); - - Assert.assertNotNull(setSeine2.getTargetSample()); - Assert.assertEquals(1, setSeine2.sizeTargetSample()); - TargetSample ec1 = setSeine2.getTargetSample().iterator().next(); - Assert.assertEquals(replicationDataModel.targetSample.getTopiaId(), ec1.getTopiaId()); - - } finally { - tx.closeContext(); - } - - } - - @Override - public final void testGetOperation() throws Exception { - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } - } - - @Test - @Override - public final void testDetectTypes() throws Exception { - Assume.assumeTrue(replicationDataModel != null); - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } - Assert.assertFalse(replicationDataModel.setSeine.isSchoolEstimateEmpty()); - Assert.assertNotNull(replicationDataModel.setSeine.getSchoolEstimateByTopiaId(replicationDataModel.schoolEstimate.getTopiaId())); - Assert.assertNotNull(replicationDataModel.schoolEstimate.getSetSeine()); - Assert.assertNotNull(replicationDataModel.targetCatch.getSetSeine()); - - detectTypes(replicationDataModel.floatingObject, FloatingObject.class); - detectTypes(replicationDataModel.setSeine, SetSeine.class, SchoolEstimate.class, TargetSample.class, TargetLength.class, TargetCatch.class, NonTargetCatch.class); - detectTypes(replicationDataModel.activitySeine, ActivitySeine.class, SetSeine.class, SchoolEstimate.class, FloatingObject.class, TargetSample.class, TargetLength.class, TargetCatch.class, NonTargetCatch.class); - detectTypes(replicationDataModel.route, Route.class, ActivitySeine.class, SetSeine.class, SchoolEstimate.class, FloatingObject.class, TargetSample.class, TargetLength.class, TargetCatch.class, NonTargetCatch.class); - detectTypes(replicationDataModel.tripSeine, TripSeine.class, Route.class, ActivitySeine.class, SetSeine.class, SchoolEstimate.class, FloatingObject.class, TargetSample.class, TargetLength.class, TargetCatch.class, NonTargetCatch.class); - detectTypes(replicationDataModel.programSeine); - } - - @Test - @Override - public final void testDetectAssociations() throws Exception { - Assume.assumeTrue(replicationDataModel != null); - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } - detectAssociations(replicationDataModel.floatingObject); - - detectAssociations(replicationDataModel.setSeine, - ObserveEntityEnum.SetSeine, SetSeine.PROPERTY_SCHOOL_ESTIMATE); - - detectAssociations(replicationDataModel.activitySeine, - ObserveEntityEnum.ActivitySeine, ActivitySeine.PROPERTY_FLOATING_OBJECT, - ObserveEntityEnum.SetSeine, SetSeine.PROPERTY_SCHOOL_ESTIMATE); - - detectAssociations(replicationDataModel.route, - ObserveEntityEnum.Route, Route.PROPERTY_ACTIVITY_SEINE, - ObserveEntityEnum.ActivitySeine, ActivitySeine.PROPERTY_FLOATING_OBJECT, - ObserveEntityEnum.SetSeine, SetSeine.PROPERTY_SCHOOL_ESTIMATE); - - detectAssociations(replicationDataModel.tripSeine, - ObserveEntityEnum.TripSeine, TripSeine.PROPERTY_ROUTE, - ObserveEntityEnum.Route, Route.PROPERTY_ACTIVITY_SEINE, - ObserveEntityEnum.ActivitySeine, ActivitySeine.PROPERTY_FLOATING_OBJECT, - ObserveEntityEnum.SetSeine, SetSeine.PROPERTY_SCHOOL_ESTIMATE); - - detectAssociations(replicationDataModel.programSeine); - } - - @Test - @Override - public final void testDetectDirectDependencies() throws Exception { - Assume.assumeTrue(replicationDataModel != null); - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } - detectDirectDependencies( - replicationDataModel.floatingObject - ); - - detectDirectDependencies( - replicationDataModel.setSeine, - ObserveEntityEnum.SchoolEstimate, SchoolEstimate.PROPERTY_SET_SEINE); - - detectDirectDependencies( - replicationDataModel.activitySeine, - ObserveEntityEnum.SchoolEstimate, SchoolEstimate.PROPERTY_SET_SEINE, - ObserveEntityEnum.ActivitySeine, ActivitySeine.PROPERTY_SET_SEINE); - - detectDirectDependencies( - replicationDataModel.route, - ObserveEntityEnum.SchoolEstimate, SchoolEstimate.PROPERTY_SET_SEINE, - ObserveEntityEnum.ActivitySeine, ActivitySeine.PROPERTY_SET_SEINE); - - detectDirectDependencies( - replicationDataModel.tripSeine, - ObserveEntityEnum.SchoolEstimate, SchoolEstimate.PROPERTY_SET_SEINE, - ObserveEntityEnum.ActivitySeine, ActivitySeine.PROPERTY_SET_SEINE); - - detectDirectDependencies(replicationDataModel.programSeine); - } - - @Test - @Override - public final void testDetectShell() throws Exception { - Assume.assumeTrue(replicationDataModel != null); - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } - detectShell(replicationDataModel.floatingObject, - ObserveEntityEnum.ObjectSchoolEstimate, - ObserveEntityEnum.ObjectObservedSpecies, - ObserveEntityEnum.TransmittingBuoy - ); - detectShell(replicationDataModel.schoolEstimate, - ObserveEntityEnum.SetSeine, - ObserveEntityEnum.TargetCatch, - ObserveEntityEnum.TargetSample, - ObserveEntityEnum.TargetLength, - ObserveEntityEnum.NonTargetCatch, - ObserveEntityEnum.NonTargetSample, - ObserveEntityEnum.NonTargetLength - ); - detectShell(replicationDataModel.setSeine, - ObserveEntityEnum.SchoolEstimate, - ObserveEntityEnum.TargetCatch, - ObserveEntityEnum.TargetSample, - ObserveEntityEnum.TargetLength, - ObserveEntityEnum.NonTargetCatch, - ObserveEntityEnum.NonTargetSample, - ObserveEntityEnum.NonTargetLength - ); - detectShell(replicationDataModel.activitySeine, - ObserveEntityEnum.SetSeine, - ObserveEntityEnum.SchoolEstimate, - ObserveEntityEnum.FloatingObject, - ObserveEntityEnum.TargetCatch, - ObserveEntityEnum.TargetSample, - ObserveEntityEnum.TargetLength, - ObserveEntityEnum.NonTargetCatch, - ObserveEntityEnum.NonTargetSample, - ObserveEntityEnum.NonTargetLength, - ObserveEntityEnum.ObjectSchoolEstimate, - ObserveEntityEnum.ObjectObservedSpecies, - ObserveEntityEnum.TransmittingBuoy - ); - detectShell(replicationDataModel.route, - ObserveEntityEnum.ActivitySeine, - ObserveEntityEnum.SetSeine, - ObserveEntityEnum.SchoolEstimate, - ObserveEntityEnum.FloatingObject, - ObserveEntityEnum.TargetCatch, - ObserveEntityEnum.TargetSample, - ObserveEntityEnum.TargetLength, - ObserveEntityEnum.NonTargetCatch, - ObserveEntityEnum.NonTargetSample, - ObserveEntityEnum.NonTargetLength, - ObserveEntityEnum.ObjectSchoolEstimate, - ObserveEntityEnum.ObjectObservedSpecies, - ObserveEntityEnum.TransmittingBuoy - ); - detectShell(replicationDataModel.tripSeine, - ObserveEntityEnum.Route, - ObserveEntityEnum.GearUseFeaturesSeine, - ObserveEntityEnum.GearUseFeaturesMeasurementSeine, - ObserveEntityEnum.ActivitySeine, - ObserveEntityEnum.SetSeine, - ObserveEntityEnum.SchoolEstimate, - ObserveEntityEnum.FloatingObject, - ObserveEntityEnum.TargetCatch, - ObserveEntityEnum.TargetSample, - ObserveEntityEnum.TargetLength, - ObserveEntityEnum.NonTargetCatch, - ObserveEntityEnum.NonTargetSample, - ObserveEntityEnum.NonTargetLength, - ObserveEntityEnum.ObjectSchoolEstimate, - ObserveEntityEnum.ObjectObservedSpecies, - ObserveEntityEnum.TransmittingBuoy - ); - } - - /** - * FIXME On ne sait pas gerer pour le moment les cycles. - * - * @throws Exception pour toute erreur - */ - @Ignore - @Test - @Override - public final void testDetectObjectsToDettach() throws Exception { - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } - detectObjectsToDettach(replicationDataModel.floatingObject); - detectObjectsToDettach(replicationDataModel.schoolEstimate, ObserveEntityEnum.SetSeine, new String[]{SetSeine.PROPERTY_SCHOOL_ESTIMATE}); - detectObjectsToDettach(replicationDataModel.setSeine, ObserveEntityEnum.SetSeine, new String[]{SetSeine.PROPERTY_SCHOOL_ESTIMATE}); - detectObjectsToDettach(replicationDataModel.activitySeine, ObserveEntityEnum.SetSeine, new String[]{SetSeine.PROPERTY_SCHOOL_ESTIMATE}); - detectObjectsToDettach(replicationDataModel.route, ObserveEntityEnum.SetSeine, new String[]{SetSeine.PROPERTY_SCHOOL_ESTIMATE}); - detectObjectsToDettach(replicationDataModel.tripSeine, ObserveEntityEnum.SetSeine, new String[]{SetSeine.PROPERTY_SCHOOL_ESTIMATE}); - detectObjectsToDettach(replicationDataModel.programSeine, ObserveEntityEnum.SetSeine, new String[]{SetSeine.PROPERTY_SCHOOL_ESTIMATE}); - } - - /** - * FIXME OOn ne sait pas gerer pour le moment les cycles. - * - * @throws Exception pour tout erreur - */ - @Ignore - @Test - @Override - public final void testDetectDependencies() throws Exception { - if (getLog().isDebugEnabled()) { - getLog().debug("start test"); - } - detectDependencies( - replicationDataModel.floatingObject, - new ObserveEntityEnum[]{ObserveEntityEnum.FloatingObject} - ); - detectDependencies( - replicationDataModel.schoolEstimate, - new ObserveEntityEnum[]{ObserveEntityEnum.SetSeine}, - new ObserveEntityEnum[]{ObserveEntityEnum.SchoolEstimate} - ); - detectDependencies( - replicationDataModel.setSeine, - new ObserveEntityEnum[]{ObserveEntityEnum.SetSeine}, - new ObserveEntityEnum[]{ObserveEntityEnum.SchoolEstimate} - ); - detectDependencies( - replicationDataModel.activitySeine, - new ObserveEntityEnum[]{ObserveEntityEnum.SetSeine}, - new ObserveEntityEnum[]{ - ObserveEntityEnum.SchoolEstimate, - ObserveEntityEnum.FloatingObject - }, - new ObserveEntityEnum[]{ObserveEntityEnum.ActivitySeine} - ); - detectDependencies( - replicationDataModel.route, - new ObserveEntityEnum[]{ObserveEntityEnum.SetSeine}, - new ObserveEntityEnum[]{ObserveEntityEnum.SchoolEstimate, ObserveEntityEnum.FloatingObject}, - new ObserveEntityEnum[]{ObserveEntityEnum.ActivitySeine}, new ObserveEntityEnum[]{ObserveEntityEnum.Route} - ); - detectDependencies( - replicationDataModel.tripSeine, - new ObserveEntityEnum[]{ObserveEntityEnum.SetSeine}, - new ObserveEntityEnum[]{ObserveEntityEnum.SchoolEstimate, ObserveEntityEnum.FloatingObject}, - new ObserveEntityEnum[]{ObserveEntityEnum.ActivitySeine}, - new ObserveEntityEnum[]{ObserveEntityEnum.Route}, - new ObserveEntityEnum[]{ObserveEntityEnum.TripSeine} - ); - detectDependencies(replicationDataModel.programSeine); - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateReferentielTest.java b/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateReferentielTest.java deleted file mode 100644 index bf82b89..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateReferentielTest.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.replication; - -import fr.ird.observe.entities.Entities; -import fr.ird.observe.ObserveDAOHelper; -import fr.ird.observe.ObserveEntityEnum; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.entities.seine.TripSeine; -import fr.ird.observe.entities.referentiel.Country; -import fr.ird.observe.entities.referentiel.Vessel; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.referentiel.Program; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; - -import java.util.Date; -import java.util.List; - -/** @author Tony Chemit - chemit@codelutin.com */ -public abstract class AbstractReplicateReferentielTest extends AbstractReplicateTest { - - static protected Program program; - - static protected Country country; - - static protected TripSeine maree; - - static protected Species species; - - static protected Vessel vessel; - - @Before - @Override - public void setUp() throws Exception { - - super.setUp(); - - maree = update(maree); - maree.setProgram(null); - program = update(program); - species = update(species); - vessel = update(vessel); - country = update(country); - } - - @Override - protected final void createModel(TopiaEntity entity) { - model = service.getModelBuilder().createModelForAll(getContracts()); - } - - @Override - protected final void prepareModel(String... ids) { - model = service.prepareForAll(getContracts()); - } - - @Override - protected final TopiaEntityEnum[] getContracts() { - return Entities.REFERENCE_ENTITIES; - } - - @Override - protected final void createModel(DataSource service) throws TopiaException, DataSourceException { - TopiaContext tx = service.beginTransaction("createModel"); - try { - - List<Program> programs = ObserveDAOHelper.getProgramDAO(tx).findAll(); - Assert.assertTrue(programs.isEmpty()); - - program = ObserveDAOHelper.getProgramDAO(tx).create(Program.PROPERTY_CODE, "1", Program.PROPERTY_LABEL2, "program-1"); - country = ObserveDAOHelper.getCountryDAO(tx).create(Country.PROPERTY_CODE, "1", Country.PROPERTY_LABEL2, "country-1"); - vessel = ObserveDAOHelper.getVesselDAO(tx).create(Vessel.PROPERTY_CODE, "1", Vessel.PROPERTY_LABEL2, "vessel-1", Vessel.PROPERTY_FLAG_COUNTRY, country); - - species = ObserveDAOHelper.getSpeciesDAO(tx).create(Species.PROPERTY_CODE, "1"); - - maree = ObserveDAOHelper.getTripSeineDAO(tx).create(TripSeine.PROPERTY_START_DATE, new Date()); - - service.commitTransaction(tx, "createModel"); - - } finally { - service.closeTransaction(tx, "createModel"); - } - } - - @Test - @Override - public final void testDetectTypes() throws Exception { - - - detectTypes(program, Program.class); - detectTypes(species, Species.class); - detectTypes(vessel, Vessel.class, Country.class); - detectTypes(country, Country.class); - detectTypes(maree); - } - - @Test - @Override - public final void testDetectAssociations() throws Exception { - - detectAssociations(program); - detectAssociations(country); - detectAssociations(vessel); - detectAssociations(species); - } - - @Test - @Override - public final void testDetectDirectDependencies() throws Exception { - - detectDirectDependencies(program); - detectDirectDependencies(country); - detectDirectDependencies(species); - detectDirectDependencies( - vessel, - ObserveEntityEnum.Vessel, Vessel.PROPERTY_FLAG_COUNTRY, - ObserveEntityEnum.Vessel, Vessel.PROPERTY_VESSEL_SIZE_CATEGORY, - ObserveEntityEnum.Vessel, Vessel.PROPERTY_VESSEL_TYPE); - } - - @Test - @Override - public final void testDetectShell() throws Exception { - - detectShell(country); - detectShell(program, - ObserveEntityEnum.Organism, - ObserveEntityEnum.Country - ); - detectShell(species, - ObserveEntityEnum.SpeciesGroup, - ObserveEntityEnum.Ocean - ); - detectShell(vessel, - ObserveEntityEnum.Country, - ObserveEntityEnum.VesselSizeCategory, - ObserveEntityEnum.VesselType - ); - } - - @Test - @Override - public final void testDetectDependencies() throws Exception { - - detectDependencies(null, - new ObserveEntityEnum[]{ - ObserveEntityEnum.VesselType, - ObserveEntityEnum.Country, - ObserveEntityEnum.VesselSizeCategory, - ObserveEntityEnum.Species,}, - new ObserveEntityEnum[]{ - ObserveEntityEnum.Wind, - ObserveEntityEnum.Program - } - ); - } - - @Test - @Override - public final void testDetectObjectsToDettach() throws Exception { - - detectObjectsToDettach(null); - } - - @Test - @Override - public final void testDetectOperations() throws Exception { - - detectOperations(null); - } - - @Test - @Override - public final void testDoReplicate() throws Exception { - - doReplicateAll(); - - // on attache une maree - TopiaContext tx = ctxt.beginTransaction(); - - TopiaDAO<TripSeine> dao = ((TopiaContextImplementor) tx).getDAO(TripSeine.class); - - maree = dao.findByTopiaId(maree.getTopiaId()); - maree.setProgram(program); - - dao.update(maree); - - tx.commitTransaction(); - tx.closeContext(); - try { - doReplicateAll(); - } finally { - tx = ctxt.beginTransaction(); - - dao = ((TopiaContextImplementor) tx).getDAO(TripSeine.class); - maree = dao.findByTopiaId(maree.getTopiaId()); - maree.setProgram(null); - - dao.update(maree); - tx.commitTransaction(); - tx.closeContext(); - } - - -// // le test casse car la maree attache n'est pas dupliquee -// try { -// doReplicateAll(); -// fail(); -// } catch (Throwable e) { -// log.error(e.getMessage(), e); -// assertTrue(true); -// } - - } - - @Test - public final void testDoReplicateFromService() throws Exception { - - TopiaContext dstDb = createDb2("testDoReplicateFromService"); - - localService.getReplicationService().replicateReferentiel(localService, dbCible); -// localService.replicateReferentiel(dbCible); - - TopiaContext tx = ctxt.beginTransaction(); - TopiaContext tx2 = dstDb.beginTransaction(); - - try { - assertDbEquals(getContracts(), - (TopiaContextImplementor) tx, - (TopiaContextImplementor) tx2 - ); - - } finally { - tx.closeContext(); - tx2.closeContext(); - } - } - - @Override - public final void testGetOperation() throws Exception { - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateTest.java b/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateTest.java deleted file mode 100644 index 6c146d6..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/AbstractReplicateTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.replication; - -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.replication.AbstractTopiaReplicationServiceTest; - -import java.io.File; - -public abstract class AbstractReplicateTest extends AbstractTopiaReplicationServiceTest { - - static protected DataSource localService; - - protected DataSource dbCible; - - @AfterClass - public static void after() throws Exception { - DataSourceFactory.dispose(); - AbstractTopiaReplicationServiceTest.after(); - - if (DBTestHelper.canUsePG) { - - // restore last pg empty test database - DBTestHelper.restoreEmptyPG("restoreEmptyPGFor :: " + DBTestHelper.testClass); - } - } - - @After - @Override - public final void tearDown() throws Exception { - - if (dbCible != null && dbCible.isOpen()) { - dbCible.doClose(false); - } - - super.tearDown(); - - } - - protected abstract DataSource createStorage(String name) throws Exception; - - protected final DataSource createStorage2(String name) throws Exception { - File dir = new File(getTestDir(getClass()), "replicateDB_" + name); - - DataSource service = DBTestHelper.createAndOpenEmptyDb(dir, false); - return service; - } - - protected abstract void createModel(DataSource service) throws Exception; - - @Override - protected final TopiaContext createDb(String name) throws Exception { - localService = createStorage(name); - createModel(localService); - return localService.getRootCtxt(); - } - - @Override - protected final TopiaContext createDb2(String name) throws Exception { - dbCible = createStorage2(name); - return dbCible.getRootCtxt(); - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateDataIT.java b/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateDataIT.java deleted file mode 100644 index 787adee..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateDataIT.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.replication; - -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.BeforeClass; - -import java.io.File; - -/** - * Pour tester la replication de donnes complexes, a savoir des donnees ou il y - * a des cycles de detecter. - * <p/> - * Pour le moment, on ne peut pas traiter dans le service de replication de tels - * cas, on utilise la replication avec ordre fixe, i.e que l'on fixe nous meme - * l'ordre de replication. - * <p/> - * Pour le reste, le service de replication sera capable de trouver les - * objectOperations a realiser pour que la replication fonctionne. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class H2ReplicateDataIT extends AbstractReplicateDataTest { - - /** Logger */ - private static final Log log = LogFactory.getLog(H2ReplicateDataIT.class); - - @BeforeClass - public static void init() throws Exception { - - DBTestHelper.initDbForTest(H2ReplicateDataIT.class, false, false); - } - - @Override - protected DataSource createStorage(String name) throws Exception { - File dir = new File(getTestDir(getClass()), "localDB_" + name); - - DataSource service = DBTestHelper.createAndOpenEmptyDb(dir, false); - return service; - } - - - @Override - protected Log getLog() { - return log; - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateDataTest.java b/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateDataTest.java deleted file mode 100644 index 96bdcfb..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateDataTest.java +++ /dev/null @@ -1,370 +0,0 @@ -package fr.ird.observe.its.replication; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Maps; -import fr.ird.observe.ObserveEntityEnum; -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.db.DataSourceException; -import fr.ird.observe.entities.Entities; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.SetLongline; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.NonTargetSample; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TargetSample; -import fr.ird.observe.entities.seine.TripSeine; -import fr.ird.observe.test.TestHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaDAO; - -import java.io.File; -import java.io.IOException; -import java.util.EnumMap; - -/** - * Created on 4/23/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0-RC4 - */ -public class H2ReplicateDataTest { - - /** Logger. */ - private static final Log log = LogFactory.getLog(H2ReplicateDataTest.class); - - static DataSource sourceDatasource; - - static File testDir; - - public static final String TRIP_SEINE_ID = "fr.ird.observe.entities.seine.TripSeine#1429782251612#0.864032703758805"; - - public static final String TRIP_LONGLINE_ID = "fr.ird.observe.entities.longline.TripLongline#1428427025277#0.8587988145746449"; - - @BeforeClass - public static void init() throws Exception { - - DBTestHelper.initDbForTest(H2ReplicateDataTest.class, false, false); - - File sourceDbDump = new File("src/test/resources/db/replication/data.sql.gz"); - - testDir = TestHelper.getTestDir(H2ReplicateDataTest.class); - File dir = new File(testDir, "source"); - - sourceDatasource = DBTestHelper.createAndOpenFromDump(dir, sourceDbDump.toURI().toURL(), false, false, false, true, true); - - EnumMap<ObserveEntityEnum, Long> globalCount = createEmptyCounts(); - - addSeineCounts(globalCount); - addLonglineCounts(globalCount); - - assertNbEntitiesForSeine(sourceDatasource.getRootCtxt(), globalCount, TRIP_SEINE_ID); - assertNbEntitiesForLongline(sourceDatasource.getRootCtxt(), globalCount, TRIP_LONGLINE_ID); - - } - - @AfterClass - public static void close() throws Exception { - - sourceDatasource.doClose(false); - - } - - @Test - public void replicateSeineTrip() throws IOException, DataSourceException, TopiaException { - - File dir = new File(testDir, "replicateSeineTrip"); - - DataSource targetDataSource = DBTestHelper.createAndOpenEmptyDb(dir, false); - - try { - - sourceDatasource.getReplicationService().replicateReferentiel(sourceDatasource, targetDataSource); - sourceDatasource.getReplicationService().replicateData(sourceDatasource, targetDataSource, TRIP_SEINE_ID); - - EnumMap<ObserveEntityEnum, Long> replicateCounts = createEmptyCounts(); - addSeineCounts(replicateCounts); - - assertNbEntitiesForSeine(targetDataSource.getRootCtxt(), replicateCounts, TRIP_SEINE_ID); - - } finally { - - targetDataSource.doClose(false); - - } - - } - - @Test - public void replicateLonglineTrip() throws IOException, DataSourceException, TopiaException { - - File dir = new File(testDir, "replicateLonglineTrip"); - - DataSource targetDataSource = DBTestHelper.createAndOpenEmptyDb(dir, false); - - try { - - sourceDatasource.getReplicationService().replicateReferentiel(sourceDatasource, targetDataSource); - sourceDatasource.getReplicationService().replicateData(sourceDatasource, targetDataSource, TRIP_LONGLINE_ID); - - EnumMap<ObserveEntityEnum, Long> replicateCounts = createEmptyCounts(); - addLonglineCounts(replicateCounts); - - assertNbEntitiesForLongline(targetDataSource.getRootCtxt(), replicateCounts, TRIP_LONGLINE_ID); - - } finally { - - targetDataSource.doClose(false); - } - - } - - protected static EnumMap<ObserveEntityEnum, Long> createEmptyCounts() { - - EnumMap<ObserveEntityEnum, Long> result = Maps.newEnumMap(ObserveEntityEnum.class); - for (ObserveEntityEnum dataEntity : Entities.DATA_ENTITIES) { - result.put(dataEntity, 0l); - } - return result; - - } - - protected static void addSeineCounts(EnumMap<ObserveEntityEnum, Long> replicateCounts) { - - replicateCounts.put(ObserveEntityEnum.TargetSample, 2l); - replicateCounts.put(ObserveEntityEnum.TargetLength, 4l); - replicateCounts.put(ObserveEntityEnum.NonTargetSample, 1l); - replicateCounts.put(ObserveEntityEnum.NonTargetLength, 2l); - replicateCounts.put(ObserveEntityEnum.NonTargetCatch, 2l); - replicateCounts.put(ObserveEntityEnum.SetSeine, 1l); - replicateCounts.put(ObserveEntityEnum.TargetCatch, 4l); - replicateCounts.put(ObserveEntityEnum.TransmittingBuoy, 2l); - replicateCounts.put(ObserveEntityEnum.ObjectObservedSpecies, 5l); - replicateCounts.put(ObserveEntityEnum.SchoolEstimate, 2l); - replicateCounts.put(ObserveEntityEnum.ObjectSchoolEstimate, 4l); - replicateCounts.put(ObserveEntityEnum.FloatingObject, 2l); - replicateCounts.put(ObserveEntityEnum.ActivitySeine, 2l); - replicateCounts.put(ObserveEntityEnum.Route, 2l); - replicateCounts.put(ObserveEntityEnum.GearUseFeaturesMeasurementSeine, 8l); - replicateCounts.put(ObserveEntityEnum.GearUseFeaturesSeine, 1l); - replicateCounts.put(ObserveEntityEnum.TripSeine, 1l); - - } - - protected static void addLonglineCounts(EnumMap<ObserveEntityEnum, Long> replicateCounts) { - - replicateCounts.put(ObserveEntityEnum.HooksComposition, 2l); - replicateCounts.put(ObserveEntityEnum.BranchlinesComposition, 2l); - replicateCounts.put(ObserveEntityEnum.BaitsComposition, 2l); - replicateCounts.put(ObserveEntityEnum.FloatlinesComposition, 2l); - replicateCounts.put(ObserveEntityEnum.SizeMeasure, 2l); - replicateCounts.put(ObserveEntityEnum.WeightMeasure, 2l); - replicateCounts.put(ObserveEntityEnum.SetLongline, 1l); - replicateCounts.put(ObserveEntityEnum.Branchline, 2l); - replicateCounts.put(ObserveEntityEnum.Basket, 1l); - replicateCounts.put(ObserveEntityEnum.Section, 1l); - replicateCounts.put(ObserveEntityEnum.CatchLongline, 2l); - replicateCounts.put(ObserveEntityEnum.Tdr, 2l); - replicateCounts.put(ObserveEntityEnum.Encounter, 2l); - replicateCounts.put(ObserveEntityEnum.SensorUsed, 2l); - replicateCounts.put(ObserveEntityEnum.ActivityLongline, 1l); - replicateCounts.put(ObserveEntityEnum.TdrRecord, 0l); - replicateCounts.put(ObserveEntityEnum.GearUseFeaturesLongline, 1l); - replicateCounts.put(ObserveEntityEnum.GearUseFeaturesMeasurementLongline, 2l); - replicateCounts.put(ObserveEntityEnum.TripLongline, 1l); - - } - - protected static void assertNbEntitiesForSeine(TopiaContext rootTx, EnumMap<ObserveEntityEnum, Long> counts, String tripId) { - - TopiaContext tx = rootTx.beginTransaction(); - - try { - - assertNbEntities((TopiaContextImplementor) tx, counts); - - TripSeine tripSeine = (TripSeine) tx.findByTopiaId(tripId); - Assert.assertNotNull(tripSeine); - - Assert.assertFalse(tripSeine.isGearUseFeaturesSeineEmpty()); - Assert.assertEquals(1, tripSeine.sizeGearUseFeaturesSeine()); - - Assert.assertFalse(tripSeine.isRouteEmpty()); - Assert.assertEquals(2, tripSeine.sizeRoute()); - - Route route = tripSeine.getRoute().get(0); - Assert.assertNotNull(route); - - Assert.assertFalse(route.isActivitySeineEmpty()); - Assert.assertEquals(2, route.sizeActivitySeine()); - - { - ActivitySeine activitySeine = route.getActivitySeine().get(0); - Assert.assertNotNull(activitySeine); - Assert.assertNull(activitySeine.getSetSeine()); - Assert.assertFalse(activitySeine.isFloatingObjectEmpty()); - Assert.assertEquals(2, activitySeine.sizeFloatingObject()); - - { - FloatingObject floatingObject = activitySeine.getFloatingObject().get(0); - Assert.assertNotNull(floatingObject); - - Assert.assertFalse(floatingObject.isObjectObservedSpeciesEmpty()); - Assert.assertEquals(2, floatingObject.sizeObjectObservedSpecies()); - - Assert.assertFalse(floatingObject.isObjectSchoolEstimateEmpty()); - Assert.assertEquals(2, floatingObject.sizeObjectSchoolEstimate()); - - Assert.assertFalse(floatingObject.isTransmittingBuoyEmpty()); - Assert.assertEquals(1, floatingObject.sizeTransmittingBuoy()); - } - - { - FloatingObject floatingObject = activitySeine.getFloatingObject().get(1); - Assert.assertNotNull(floatingObject); - - Assert.assertFalse(floatingObject.isObjectObservedSpeciesEmpty()); - Assert.assertEquals(3, floatingObject.sizeObjectObservedSpecies()); - - Assert.assertFalse(floatingObject.isObjectSchoolEstimateEmpty()); - Assert.assertEquals(2, floatingObject.sizeObjectSchoolEstimate()); - - Assert.assertFalse(floatingObject.isTransmittingBuoyEmpty()); - Assert.assertEquals(1, floatingObject.sizeTransmittingBuoy()); - } - - } - - { - - ActivitySeine activitySeine = route.getActivitySeine().get(1); - Assert.assertNotNull(activitySeine); - Assert.assertTrue(activitySeine.isFloatingObjectEmpty()); - Assert.assertNotNull(activitySeine.getSetSeine()); - - SetSeine setSeine = activitySeine.getSetSeine(); - - Assert.assertFalse(setSeine.isNonTargetCatchEmpty()); - Assert.assertEquals(2, setSeine.sizeNonTargetCatch()); - - Assert.assertFalse(setSeine.isNonTargetSampleEmpty()); - Assert.assertEquals(1, setSeine.sizeNonTargetSample()); - - NonTargetSample nonTargetSample = setSeine.getNonTargetSample().get(0); - Assert.assertNotNull(nonTargetSample); - Assert.assertFalse(nonTargetSample.isNonTargetLengthEmpty()); - Assert.assertEquals(2, nonTargetSample.sizeNonTargetLength()); - - Assert.assertFalse(setSeine.isSchoolEstimateEmpty()); - Assert.assertEquals(2, setSeine.sizeSchoolEstimate()); - - Assert.assertFalse(setSeine.isTargetCatchEmpty()); - Assert.assertEquals(4, setSeine.sizeTargetCatch()); - - Assert.assertFalse(setSeine.isTargetSampleEmpty()); - Assert.assertEquals(2, setSeine.sizeTargetSample()); - - TargetSample targetSample = setSeine.getTargetSample().get(0); - Assert.assertNotNull(targetSample); - Assert.assertFalse(targetSample.isTargetLengthEmpty()); - Assert.assertEquals(2, targetSample.sizeTargetLength()); - - } - - - } finally { - tx.closeContext(); - } - - } - - protected static void assertNbEntitiesForLongline(TopiaContext rootTx, EnumMap<ObserveEntityEnum, Long> counts, String tripId) { - - TopiaContext tx = rootTx.beginTransaction(); - - try { - - assertNbEntities((TopiaContextImplementor) tx, counts); - - TripLongline tripLongline = (TripLongline) tx.findByTopiaId(tripId); - Assert.assertNotNull(tripLongline); - - Assert.assertFalse(tripLongline.isGearUseFeaturesLonglineEmpty()); - Assert.assertEquals(1, tripLongline.sizeGearUseFeaturesLongline()); - - Assert.assertFalse(tripLongline.isActivityLonglineEmpty()); - Assert.assertEquals(1, tripLongline.sizeActivityLongline()); - - ActivityLongline activityLongline = tripLongline.getActivityLongline().get(0); - Assert.assertNotNull(activityLongline); - - Assert.assertFalse(activityLongline.isEncounterEmpty()); - Assert.assertEquals(2, activityLongline.sizeEncounter()); - - Assert.assertFalse(activityLongline.isSensorUsedEmpty()); - Assert.assertEquals(2, activityLongline.sizeSensorUsed()); - - SetLongline setLongline = activityLongline.getSetLongline(); - Assert.assertNotNull(setLongline); - - Assert.assertFalse(setLongline.isCatchLonglineEmpty()); - Assert.assertEquals(2, setLongline.sizeCatchLongline()); - - Assert.assertFalse(setLongline.isTdrEmpty()); - Assert.assertEquals(2, setLongline.sizeTdr()); - - } finally { - tx.closeContext(); - } - - } - - - protected static void assertNbEntities(TopiaContextImplementor tx, EnumMap<ObserveEntityEnum, Long> counts) { - - for (ObserveEntityEnum dataEntity : Entities.DATA_ENTITIES) { - - TopiaDAO<?> dao = tx.getDAO(dataEntity.getContract()); - long actual = dao.count(); - long expected = counts.get(dataEntity); -// if (log.isInfoEnabled()) { -// log.info("For entity: " + dataEntity + ", expected: " + expected + ", but was: " + actual); -// } - Assert.assertEquals("For entity: " + dataEntity + ", expected: " + expected + ", but was: " + actual, expected, actual); - - } - - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateReferentielIT.java b/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateReferentielIT.java deleted file mode 100644 index d5d1129..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/H2ReplicateReferentielIT.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.replication; - -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.BeforeClass; - -import java.io.File; - -/** @author Tony Chemit - chemit@codelutin.com */ -public class H2ReplicateReferentielIT extends AbstractReplicateReferentielTest { - - /** Logger */ - private static final Log log = - LogFactory.getLog(H2ReplicateReferentielIT.class); - - @BeforeClass - public static void init() throws Exception { - - DBTestHelper.initDbForTest(H2ReplicateReferentielIT.class,false, false); - } - - @Override - protected DataSource createStorage(String name) throws Exception { - - File dir = new File(getTestDir(getClass()), "localDB_" + name); - - DataSource service = DBTestHelper.createAndOpenEmptyDb(dir, false); - - return service; - } - - @Override - protected Log getLog() { - return log; - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/PGReplicateDataIT.java b/observe-business/src/test/java/fr/ird/observe/its/replication/PGReplicateDataIT.java deleted file mode 100644 index 697443a..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/PGReplicateDataIT.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.replication; - -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.BeforeClass; - -/** - * Pour tester la replication de donnes complexes, a savoir des donnees ou il y - * a des cycles de detecter. - * <p/> - * Pour le moment, on ne peut pas traiter dans le service de replication de tels - * cas, on utilise la replication avec ordre fixe, i.e que l'on fixe nous meme - * l'ordre de replication. - * <p/> - * Pour le reste, le service de replication sera capable de trouver les - * objectOperations a realiser pour que la replication fonctionne. - * - * @author Tony Chemit - chemit@codelutin.com - */ -//@Ignore -public class PGReplicateDataIT extends AbstractReplicateDataTest { - - /** Logger */ - private static final Log log = - LogFactory.getLog(PGReplicateDataIT.class); - - @BeforeClass - public static void init() throws Exception { - - DBTestHelper.initDbForTest(PGReplicateReferentielIT.class, false, true); - } - - @Override - protected DataSource createStorage(String name) throws Exception { - - try { - DataSource service = - DBTestHelper.loadRemoteDbReferentiel(name, true); - return service; - } catch (Exception e) { - if (getLog().isErrorEnabled()) { - getLog().error(e); - } - throw e; - } - } - - @Override - protected Log getLog() { - return log; - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/PGReplicateReferentielIT.java b/observe-business/src/test/java/fr/ird/observe/its/replication/PGReplicateReferentielIT.java deleted file mode 100644 index 2c9a5d8..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/PGReplicateReferentielIT.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.replication; - -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.BeforeClass; -import org.junit.Ignore; - -/** @author Tony Chemit - chemit@codelutin.com */ -@Ignore -public class PGReplicateReferentielIT extends AbstractReplicateReferentielTest { - - /** Logger */ - private static final Log log = - LogFactory.getLog(PGReplicateReferentielIT.class); - - @BeforeClass - public static void init() throws Exception { - - DBTestHelper.initDbForTest(PGReplicateReferentielIT.class,false, true); - } - - @Override - protected DataSource createStorage(String name) throws Exception { - - DataSource service = DBTestHelper.loadRemoteDbReferentiel(name, true); - return service; - } - - @Override - protected Log getLog() { - return log; - } - -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/replication/ReplicationDataModel.java b/observe-business/src/test/java/fr/ird/observe/its/replication/ReplicationDataModel.java deleted file mode 100644 index 6ceeff8..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/replication/ReplicationDataModel.java +++ /dev/null @@ -1,170 +0,0 @@ -package fr.ird.observe.its.replication; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.DataSource; -import fr.ird.observe.entities.longline.ActivityLongline; -import fr.ird.observe.entities.longline.SetLongline; -import fr.ird.observe.entities.longline.TripLongline; -import fr.ird.observe.entities.referentiel.Country; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.referentiel.Vessel; -import fr.ird.observe.entities.referentiel.seine.WeightCategory; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.NonTargetCatch; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.SchoolEstimate; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.TargetCatch; -import fr.ird.observe.entities.seine.TargetLength; -import fr.ird.observe.entities.seine.TargetSample; -import fr.ird.observe.entities.seine.TripSeine; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; - -import org.nuiton.topia.persistence.TopiaEntity; - -import java.util.Date; - -/** - * TODO Complete it with Longline model. - * - * Created on 2/5/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class ReplicationDataModel { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReplicationDataModel.class); - - protected Program programSeine; - - protected Program programLongline; - - protected Country country; - - protected Route route; - - protected TripSeine tripSeine; - - protected TripLongline tripLongline; - - protected ActivitySeine activitySeine; - - protected ActivityLongline activityLongline; - - protected SetSeine setSeine; - - protected SetLongline setLongline; - - protected FloatingObject floatingObject; - - protected SchoolEstimate schoolEstimate; - - protected Species species; - - protected Species speciesFaune; - - protected WeightCategory weightCategory; - - protected TargetCatch targetCatch; - - protected NonTargetCatch nonTargetCatch; - - protected TargetLength targetLength; - - protected TargetSample targetSample; - - protected Vessel vessel; - - public void createModel(DataSource service, TopiaContext tx) { - - programSeine = service.getDAO(tx, Program.class).create(Program.PROPERTY_CODE, "9999", Program.PROPERTY_LABEL2, "program-1-Seine"); - programLongline = service.getDAO(tx, Program.class).create(Program.PROPERTY_CODE, "9998", Program.PROPERTY_LABEL2, "program-1-Longline"); - - country = service.getDAO(tx, Country.class).create(Country.PROPERTY_CODE, "9999", Country.PROPERTY_LABEL2, "country-1"); - vessel = service.getDAO(tx, Vessel.class).create(Vessel.PROPERTY_CODE, "9999", Vessel.PROPERTY_LABEL2, "vessel-1", Vessel.PROPERTY_FLAG_COUNTRY, country); - - species = service.getDAO(tx, Species.class).create(Species.PROPERTY_CODE, "9999"); - speciesFaune = service.getDAO(tx, Species.class).create(Species.PROPERTY_CODE, "9999"); - weightCategory = service.getDAO(tx, WeightCategory.class).create(WeightCategory.PROPERTY_CODE, "9999", WeightCategory.PROPERTY_SPECIES, species); - - targetSample = service.getDAO(tx, TargetSample.class).create(TargetSample.PROPERTY_NATURE, "nature"); - targetLength = service.getDAO(tx, TargetLength.class).create(TargetLength.PROPERTY_TARGET_SAMPLE, targetSample, TargetLength.PROPERTY_SPECIES, species, TargetLength.PROPERTY_COUNT, 1, TargetLength.PROPERTY_LENGTH, 1.0f); - tripSeine = service.getDAO(tx, TripSeine.class).create(TripSeine.PROPERTY_START_DATE, new Date()); - route = service.getDAO(tx, Route.class).create(Route.PROPERTY_DATE, new Date()); - activitySeine = service.getDAO(tx, ActivitySeine.class).create(ActivitySeine.PROPERTY_TIME, new Date()); - setSeine = service.getDAO(tx, SetSeine.class).create(SetSeine.PROPERTY_START_TIME, new Date()); - floatingObject = service.getDAO(tx, FloatingObject.class).create(FloatingObject.PROPERTY_SUPPORT_VESSEL_NAME, "supportVesselName"); - targetCatch = service.getDAO(tx, TargetCatch.class).create( - TargetCatch.PROPERTY_SET_SEINE, setSeine, - TargetCatch.PROPERTY_WEIGHT_CATEGORY, weightCategory, - TargetCatch.PROPERTY_CATCH_WEIGHT, 1.0f); - - schoolEstimate = service.getDAO(tx, SchoolEstimate.class).create( - SchoolEstimate.PROPERTY_TOTAL_WEIGHT, 10, - SchoolEstimate.PROPERTY_SET_SEINE, setSeine, - SchoolEstimate.PROPERTY_SPECIES, species); - - nonTargetCatch = service.getDAO(tx, NonTargetCatch.class).create( - NonTargetCatch.PROPERTY_SPECIES, speciesFaune - ); - - tripSeine.setProgram(programSeine); - tripSeine.addRoute(route); - route.addActivitySeine(activitySeine); - activitySeine.addFloatingObject(floatingObject); - activitySeine.setSetSeine(setSeine); - targetSample.addTargetLength(targetLength); - setSeine.addTargetSample(targetSample); - setSeine.addNonTargetCatch(nonTargetCatch); - - } - - public void update(TopiaContext ctxt) { - - programSeine = (Program) ctxt.findByTopiaId(programSeine.getTopiaId()); - setSeine = update(ctxt, setSeine); - activitySeine = update(ctxt, activitySeine); - tripSeine = update(ctxt, tripSeine); - route = update(ctxt, route); - schoolEstimate = update(ctxt, schoolEstimate); - species = update(ctxt, species); - speciesFaune = update(ctxt, speciesFaune); - targetCatch = update(ctxt, targetCatch); - nonTargetCatch = update(ctxt, nonTargetCatch); - floatingObject = update(ctxt, floatingObject); - targetLength = update(ctxt, targetLength); - targetSample = update(ctxt, targetSample); - - } - - protected <E extends TopiaEntity> E update(TopiaContext ctxt, E e) { - return (E) ctxt.findByTopiaId(e.getTopiaId()); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/AbstractReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/AbstractReportIT.java deleted file mode 100644 index 2ff0a7e..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/AbstractReportIT.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report; - -import fr.ird.observe.IObserveConfig; -import fr.ird.observe.ObserveServiceHelper; -import fr.ird.observe.entities.seine.TripSeine; -import fr.ird.observe.test.TestHelper; -import fr.ird.observe.db.DBTestHelper; -import fr.ird.observe.db.DataSource; -import fr.ird.observe.entities.migration.AbstractDataSourceMigration; -import fr.ird.observe.report.ReportBuilder; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportExecute; -import fr.ird.observe.report.model.ReportRequest; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.config.ApplicationConfig; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Classe abstraite de test d'un report. - * <p/> - * On définit ici le mécanisme pour tester unitairement un report et son - * résultat. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public abstract class AbstractReportIT { - - /** Logger */ - private static final Log log = LogFactory.getLog(AbstractReportIT.class); - - /** La liste de tous les reports connus. */ - protected static List<Report> reports; - - private static final String DATABASE_PATH_PATTERN = "/reports/%s.sql.gz"; - - /** Le lastName du report à tester. */ - protected final String reportId; - - /** La base de test chargée à partir du la sauvegarde. */ - private DataSource dataSource; - - /** Le report à tester. */ - private Report report; - - /** La maree sur laquelle on va tester le report. */ - private String tripId; - - protected AbstractReportIT() { - String packageName = getClass().getPackage().getName(); - int i = packageName.lastIndexOf("."); - reportId = packageName.substring(i + 1); - } - - @Before - public final void setUp() throws Exception { - - TestHelper.initTest(getClass()); - TestHelper.createApplicationContext(); - - ApplicationConfig config = - ObserveServiceHelper.get().getContextValue(ApplicationConfig.class); - config.setOption(IObserveConfig.DB_VERSION, DBTestHelper.V_LAST.toString()); - - TestHelper.setConfig(AbstractDataSourceMigration.AUTO_MIGRATE, "true"); - - File testDir = new File(TestHelper.getTestDir(getClass()), reportId); - - // recuperation du report à tester - report = getReport(log, reportId); - - if (log.isInfoEnabled()) { - log.info("Will use report '" + report + "'"); - } - - URL dumpLocation = getDumpURL(); - - if (log.isInfoEnabled()) { - log.info("Load db from " + dumpLocation + " to " + testDir); - } - - // chargement de la base de test - dataSource = DBTestHelper.createAndOpenFromDump( - testDir, - dumpLocation, - false, - false, - true, - false, - false - ); - - // recuperation de la maree a utiliser - List<TripSeine> marees = ObserveServiceHelper.getDataService().getList(dataSource, TripSeine.class); - Assert.assertFalse("No maree found in " + dataSource.getLabel(), marees.isEmpty()); - Assert.assertEquals("Should have found exactly one maree, but was " + marees.size(), 1, marees.size()); - - tripId = marees.get(0).getTopiaId(); - - if (log.isInfoEnabled()) { - log.info("Will use " + tripId); - } - } - - protected String getDatabaseId() { - return reportId; - } - - protected final URL getDumpURL() { - - String databaseId = getDatabaseId(); - String path = String.format(DATABASE_PATH_PATTERN, databaseId); - URL dumpLocation = getClass().getResource(path); - return dumpLocation; - } - - @After - public final void tearDown() throws Exception { - ObserveServiceHelper.get().close(); - ObserveServiceHelper.close(); - } - - /** - * L'unique test à lancer. - * <p/> - * On vérifie : - * <ul> - * <li>la syntaxe du report via {@link #testReportSyntax(Report)}</li> - * <li>le résultat du report via {@link #testReportResult(DataMatrix)}</li> - * </ul> - * - * @throws Exception pour toute erreur lors de l'execution du report - */ - @Test - public final void testReport() throws Exception { - - // test de la syntaxe du report - testReportSyntax(report); - - // creation de l'executeur de report - ReportExecute reportExecute = new ReportExecute(); - reportExecute.setSource(dataSource); - reportExecute.populate(report, tripId); - - // les variables a utiliser (par defaut, pas de variable) - Map<String, Object> variables = new HashMap<String, Object>(); - - // preparation des variables - prepareVariables(dataSource, variables); - - // une fois les variables préparées, on doit pouvoir executer le report - Assert.assertTrue(reportExecute.canExecute(variables)); - - // on execute le report - DataMatrix result = reportExecute.execute(variables); - - if (log.isInfoEnabled()) { - log.info("Result :\n" + result.getClipbordContent(true, true)); - } - - // on verifie le resultat - testReportResult(result); - } - - protected void prepareVariables(DataSource dataSource, - Map<String, Object> variables) { - variables.put(ReportExecute.TRIP_ID_VARIABLE, tripId); - } - - protected abstract void testReportSyntax(Report report); - - protected abstract void testReportResult(DataMatrix result); - - protected static Report getReport(Log log, String reportId) throws IOException { - if (reports == null) { - - URL reportLocation = - AbstractReportIT.class.getResource("/observe-reports.properties"); - - if (log.isInfoEnabled()) { - log.info("Loading reports from " + reportLocation); - } - - ReportBuilder builder = new ReportBuilder(); - - reports = builder.load(reportLocation); - - builder.clear(); - - Assert.assertNotNull(reports); - Assert.assertFalse(reports.isEmpty()); - } - - Report result = null; - // recuperation du report à tester - for (Report report : reports) { - if (reportId.equals(report.getId())) { - result = report; - break; - } - } - - Assert.assertNotNull("Could not find report with id " + reportId, reports); - return result; - } - - protected void assertReportName(Report report, - String name, - String description) { - Assert.assertEquals(reportId, report.getId()); - Assert.assertEquals(name, report.getName()); - Assert.assertEquals(description, report.getDescription()); - } - - protected void assertReportDimension(Report report, - int rows, - int columns, - String[] columnsHeader, - String[] rowsHeader) { - Assert.assertEquals(rows, report.getRows()); - Assert.assertEquals(columns, report.getColumns()); - Assert.assertArrayEquals(columnsHeader, report.getColumnHeaders()); - Assert.assertArrayEquals(rowsHeader, report.getRowHeaders()); - } - - protected void assertReportNbRequests(Report report, int nbRequests) { - ReportRequest[] requests = report.getRequests(); - Assert.assertNotNull(requests); - Assert.assertEquals(nbRequests, requests.length); - } - - protected void assertReportRequestDimension(ReportRequest request, - ReportRequest.RequestLayout layout, - int x, - int y) { - Assert.assertEquals(layout, request.getLayout()); -// Assert.assertEquals(new Point(width, height), request.getLocation()); - Assert.assertEquals(x, request.getX()); - Assert.assertEquals(y, request.getY()); - } - - protected void assertResultDimension(DataMatrix result, - int width, - int height, - int x, - int y) { - Assert.assertEquals(width, result.getWidth()); - Assert.assertEquals(height, result.getHeight()); - Assert.assertEquals(x, result.getX()); - Assert.assertEquals(y, result.getY()); - } - - protected void assertResultRow(DataMatrix result, int rowId, Object... row) { - Object[] actualRow = result.getData()[rowId]; - Assert.assertArrayEquals(row, actualRow); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatch/Report2IT.java b/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatch/Report2IT.java deleted file mode 100644 index e6fcb0b..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatch/Report2IT.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.accessoryCatch; - -import fr.ird.observe.db.DataSource; -import fr.ird.observe.report.model.DataMatrix; - -import java.util.Map; - -/** - * Test du report {@code discardedAccessoire}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class Report2IT extends ReportIT { - - @Override - protected void prepareVariables(DataSource dataSource, - Map<String, Object> variables) { - super.prepareVariables(dataSource, variables); - variables.put("speciesGroupId", - "fr.ird.observe.entities.referentiel.SpeciesGroup#1239832683689#0.12092280503502995"); - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 3, 76, 0, 0); - - assertResultRow(result, 0, "[FAO]4AVA [sc]Abudefduf vaigiensis [fr]", "-", "+ Effectif : 3"); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatch/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatch/ReportIT.java deleted file mode 100644 index c7c5cb2..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatch/ReportIT.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.accessoryCatch; - -import fr.ird.observe.db.DataSource; -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; - -import java.util.Map; - -/** - * Test du report {@code accessoryCatch}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class ReportIT extends AbstractReportIT { - - @Override - protected String getDatabaseId() { - return "accessoryCatchByGroup"; - } - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Liste des captures accessoires selon le type de banc, filtrées par groupe", - "Afficher les captures accessoires par groupe d'espèce\n" + - "Les poids sont exprimés en tonnes." - ); - - assertReportDimension( - report, - -1, - 3, - new String[]{"Espèce", - "Banc libre", - "Banc objet", - }, - null - ); - - assertReportNbRequests(report, 3); - - ReportRequest[] requests = report.getRequests(); - - assertReportRequestDimension( - requests[0], - ReportRequest.RequestLayout.row, - 0, - 0 - ); - assertReportRequestDimension( - requests[1], - ReportRequest.RequestLayout.row, - 1, - 0 - ); - assertReportRequestDimension( - requests[2], - ReportRequest.RequestLayout.row, - 2, - 0 - ); - } - - @Override - protected void prepareVariables(DataSource dataSource, Map<String, Object> variables) { - super.prepareVariables(dataSource, variables); - variables.put("speciesGroupId", "fr.ird.observe.entities.referentiel.SpeciesGroup#1239832683689#0.7120116158620075"); - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 3, 51, 0, 0); - - assertResultRow(result, 0, "[FAO]MAE [sc]Aetobatus narinari [fr]Aigle de mer léopard", "+ Effectif : 21", "-"); - assertResultRow(result, 1, "[FAO]PTH [sc]Alopias pelagicus [fr]Renard pélagique", "-", "+ Effectif : 2"); - assertResultRow(result, 2, "[FAO]BTH [sc]Alopias superciliosus [fr]Renard à gros yeux", "-", "-"); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatchByGroup/Report2IT.java b/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatchByGroup/Report2IT.java deleted file mode 100644 index 8ccc783..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatchByGroup/Report2IT.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.accessoryCatchByGroup; - -import fr.ird.observe.db.DataSource; -import fr.ird.observe.report.model.DataMatrix; - -import java.util.Map; - -/** - * Pour tester le report {@code discardedAccessoireByGroup} - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class Report2IT extends ReportIT { - - @Override - protected void prepareVariables(DataSource dataSource, - Map<String, Object> variables) { - super.prepareVariables(dataSource, variables); - variables.put("speciesGroupId", - "fr.ird.observe.entities.referentiel.SpeciesGroup#1239832683689#0.12092280503502995"); - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 11, 1, 0, 0); - - assertResultRow(result, 0, "[FAO]4AVA [sc]Abudefduf vaigiensis [fr]", null, "3", null, null, "3", null, null, null, null, null); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatchByGroup/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatchByGroup/ReportIT.java deleted file mode 100644 index 866b4d9..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/accessoryCatchByGroup/ReportIT.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.accessoryCatchByGroup; - -import fr.ird.observe.db.DataSource; -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; - -import java.util.Map; - -/** - * Pour tester le report {@code discardedAccessoireByGroup} - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class ReportIT extends AbstractReportIT { - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Dénombrement des captures accessoires et devenir, filtrés par groupe", - "Afficher les nombres de captures accessoires par groupe d'espèce selon le type de banc et le devenir" - ); - - assertReportDimension( - report, - -1, - 11, - new String[]{"Espèce", - "Total BL", - "Total BO", - "Sorti vivant/échappé", - "Sorti mort", - "Rejeté vivant", - "Rejeté mort", - "Partiellement conservé", - "Cuve", - "Cuisine", - "Autre" - }, - null - ); - - assertReportNbRequests(report, 11); - - ReportRequest[] requests = report.getRequests(); - - assertReportRequestDimension( - requests[0], - ReportRequest.RequestLayout.row, - 0, - 0 - ); - assertReportRequestDimension( - requests[1], - ReportRequest.RequestLayout.row, - 1, - 0 - ); - assertReportRequestDimension( - requests[2], - ReportRequest.RequestLayout.row, - 2, - 0 - ); - assertReportRequestDimension( - requests[3], - ReportRequest.RequestLayout.row, - 3, - 0 - ); - assertReportRequestDimension( - requests[4], - ReportRequest.RequestLayout.row, - 4, - 0 - ); - assertReportRequestDimension( - requests[5], - ReportRequest.RequestLayout.row, - 5, - 0 - ); - assertReportRequestDimension( - requests[6], - ReportRequest.RequestLayout.row, - 6, - 0 - ); - assertReportRequestDimension( - requests[7], - ReportRequest.RequestLayout.row, - 7, - 0 - ); - assertReportRequestDimension( - requests[8], - ReportRequest.RequestLayout.row, - 8, - 0 - ); - assertReportRequestDimension( - requests[9], - ReportRequest.RequestLayout.row, - 9, - 0 - ); - assertReportRequestDimension( - requests[10], - ReportRequest.RequestLayout.row, - 10, - 0 - ); - } - - @Override - protected void prepareVariables(DataSource dataSource, Map<String, Object> variables) { - super.prepareVariables(dataSource, variables); - variables.put("speciesGroupId", "fr.ird.observe.entities.referentiel.SpeciesGroup#1239832683689#0.7120116158620075"); - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 11, 2, 0, 0); - - assertResultRow(result, 0, "[FAO]MAE [sc]Aetobatus narinari [fr]Aigle de mer léopard", "21", null, "1",null, "2", "3", "4", "5", "6", null); - assertResultRow(result, 1, "[FAO]PTH [sc]Alopias pelagicus [fr]Renard pélagique", null, "2", "2",null, null, null, null, null,null,null); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/activityWithComment/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/activityWithComment/ReportIT.java deleted file mode 100644 index a551c63..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/activityWithComment/ReportIT.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.activityWithComment; - -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; - -/** - * Pour tester le report {@code dailySetAndCapture}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class ReportIT extends AbstractReportIT { - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Activités avec comment et leurs positions", - "Afficher les activités avec comment et leurs positions géographiques" - ); - - assertReportDimension( - report, - -1, - 5, - new String[]{"Jour - Heure observation", - "Latitude", - "Longitude", - "Activité", - "Commentaire" - }, - null - ); - - assertReportNbRequests(report, 1); - - ReportRequest[] requests = report.getRequests(); - - assertReportRequestDimension( - requests[0], - ReportRequest.RequestLayout.row, - 0, - 0 - ); - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 5, 2, 0, 0); - - assertResultRow(result, 0, "13/10/2010 15:16", "10.633472", "10.650139", "Transit ( route sans recherche )", "Premier commentaire"); - - assertResultRow(result, 1, "13/10/2010 23:46", "10.650139", "10.666806", "Recherche ( général )", "Second commentaire"); - - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/allActivitys/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/allActivitys/ReportIT.java deleted file mode 100644 index bcaaa4e..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/allActivitys/ReportIT.java +++ /dev/null @@ -1,79 +0,0 @@ -package fr.ird.observe.its.report.allActivitys; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; - -/** - * Created on 7/4/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.5 - */ -public class ReportIT extends AbstractReportIT { - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Toutes les activités et leurs positions", - "Afficher toutes les activités et leurs positions géographiques" - ); - - assertReportDimension( - report, - -1, - 5, - new String[]{"Jour - Heure observation", "Latitude", "Longitude", "Activité", "Commentaire", - }, - null - ); - - assertReportNbRequests(report, 1); - - ReportRequest[] requests = report.getRequests(); - - assertReportRequestDimension( - requests[0], - ReportRequest.RequestLayout.row, - 0, - 0 - ); - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 5, 4, 0, 0); - - assertResultRow(result, 0, "13/10/2010 13:36", "10.616806", "10.633472", "Au port", null); - assertResultRow(result, 1, "13/10/2010 15:16", "10.633472", "10.650139", "Transit ( route sans recherche )", "Premier commentaire"); - assertResultRow(result, 2, "13/10/2010 18:1", "10.633472", "10.650139", "Au port", null); - assertResultRow(result, 3, "13/10/2010 23:46", "10.650139", "10.666806", "Recherche ( général )", "Second commentaire"); - - } -} \ No newline at end of file diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/dailySetAndCatch/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/dailySetAndCatch/ReportIT.java deleted file mode 100644 index 9ea0efa..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/dailySetAndCatch/ReportIT.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.dailySetAndCatch; - -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; - -/** - * Pour tester le report {@code dailySetAndCapture}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class ReportIT extends AbstractReportIT { - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Nombre de calées et captures journalières d'une marée", - "Afficher le nombre de calées et les captures journalières d’une calée" - ); - - assertReportDimension( - report, - -1, - 3, - new String[]{"Jour observation", - "Nombre de calées", - "Captures thon" - }, - null - ); - - assertReportNbRequests(report, 1); - - ReportRequest[] requests = report.getRequests(); - ReportRequest request = requests[0]; - - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - 0, - 0 - ); - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 3, 6, 0, 0); - - // la maree contient 6 routes (C=set, CT = targetCatche) - // 06/10/2010 : 1 C sans CT => 1 | null - assertResultRow(result, 0, "6/10/2010", "1", null); - - // 07/10/2010 : 1 C avec 1 CT de 1T => 1 | 1 - assertResultRow(result, 1, "7/10/2010", "1", "1.0"); - - // 08/10/2010 : 1 C sans CT + 1 C avec 1 CT de 1T => 2 | 1 - assertResultRow(result, 2, "8/10/2010", "2", "1.0"); - - // 09/10/2010 : 1 C avec 1CT de 1T et 1CT de 2T => 1 | 3 - assertResultRow(result, 3, "9/10/2010", "1", "3.0"); - - // 10/10/2010 : 1 C avec 1CT de 1T et 1CT de 2T + 1 C avec 1 CT de 5T => 2 | 8 - assertResultRow(result, 4, "10/10/2010", "2", "8.0"); - - // 11/10/2010 : 1 C sans CT + 1 C avec 1CT de 1T et 1CT de 2T + 1 C avec 1 CT de 5T => 3 | 8 - assertResultRow(result, 5, "11/10/2010", "3", "8.0"); - - - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/dcpUsage/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/dcpUsage/ReportIT.java deleted file mode 100644 index fd630b2..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/dcpUsage/ReportIT.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.dcpUsage; - -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; -import org.junit.Ignore; - -/** - * Pour tester le report {@code dcpUsage}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -//FIXME The report need to be rewritten (operations move from objet to balise lue) -@Ignore -public class ReportIT extends AbstractReportIT { - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Utilisation des DCP", - "Tableau récapitulatif du count de DCP visités selon l’action effectuée (visites avec et sans pêche, mis à l’eau, récuperation), et tortues observées" - ); - - assertReportDimension( - report, - -1, - 6, - new String[]{"Type de DCP (Tableau 8)", - "Nombre visités", - "Nombre pêchés", - "Nombre mis à l’eau", - "Récupéré sans pêche", - "Nombre de tortues associées" - }, - null - ); - - assertReportNbRequests(report, 6); - - ReportRequest[] requests = report.getRequests(); - ReportRequest request; - - request = requests[0]; - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - 0, - 0 - ); - - request = requests[1]; - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - 1, - 0 - ); - - request = requests[2]; - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - 2, - 0 - ); - request = requests[3]; - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - 3, - 0 - ); - - request = requests[4]; - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - 4, - 0 - ); - request = requests[5]; - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - 5, - 0 - ); - } - - @Override - protected void testReportResult(DataMatrix result) { - - // 4 DCP dans une maree - assertResultDimension(result, 6, 4, 0, 0); - - // dcp code 1 : mise à l'eau - assertResultRow(result, 0, "1 - tas de paille", "0", "0", "1", "0", null); - - // dcp code 3 visité - assertResultRow(result, 1, "3 - Arbre ( ou branche )", "1", "0", "0", "1", null); - - // dcp code 2 pêche (count 10) - assertResultRow(result, 2, "2 - Palme de cocotier / palmier", "0", "1", "0", "0", null); - - // dcp code 4 visité, mise à l'eau, peche (count 23) - assertResultRow(result, 3, "4 - Charogne ( préciser la nature dans les notes )", "1", "1", "1", "0", null); - - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/setByAssociation/Report2IT.java b/observe-business/src/test/java/fr/ird/observe/its/report/setByAssociation/Report2IT.java deleted file mode 100644 index d4bc37d..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/setByAssociation/Report2IT.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.setByAssociation; - -import fr.ird.observe.report.model.DataMatrix; - -/** - * Pour tester le report {@code dailySetAndCapture}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class Report2IT extends ReportIT { - - @Override - protected String getDatabaseId() { - return super.getDatabaseId() + "2"; - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 5, 3, 0, 0); - - // les 8 sets qu test 1 - // 10 calées representant chaque cas (set +, -) sur les 4 types - // d'association (le cas du BL sans 11 est traité 2 fois : une fois - // sans SO et une fois avec un BL spécifié) - assertResultRow(result, 0, "3", "2", "2", "2", "9"); - assertResultRow(result, 1, "3", "2", "2", "2", "9"); - assertResultRow(result, 2, "6", "4", "4", "4", "18"); - - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/setByAssociation/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/setByAssociation/ReportIT.java deleted file mode 100644 index 727178d..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/setByAssociation/ReportIT.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.setByAssociation; - -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; - -/** - * Pour tester le report {@code setByAssociation}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class ReportIT extends AbstractReportIT { - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Nombre de calées selon le type d’association", - "Afficher la répartitions des calées selon le type d’association l’issue du coup. Les coups sur BL baleine et BO requin-baleine sont spécifiés." - ); - - assertReportDimension( - report, - 3, - 5, - new String[]{"BL sans baleine", - "BL avec baleine", - "BO avec requin-baleine", - "BO sans requin-baleine", - "Total" - }, - new String[]{"Coups positifs", "Coups nuls", "Total"} - ); - - assertReportNbRequests(report, 8); - - ReportRequest[] requests = report.getRequests(); - - assertReportRequestDimension( - requests[0], - ReportRequest.RequestLayout.column, - 0, - 0 - ); - assertReportRequestDimension( - requests[1], - ReportRequest.RequestLayout.column, - 0, - 1 - ); - assertReportRequestDimension( - requests[2], - ReportRequest.RequestLayout.column, - 1, - 0 - ); - assertReportRequestDimension( - requests[3], - ReportRequest.RequestLayout.column, - 1, - 1 - ); - assertReportRequestDimension( - requests[4], - ReportRequest.RequestLayout.column, - 2, - 0 - ); - assertReportRequestDimension( - requests[5], - ReportRequest.RequestLayout.column, - 2, - 1 - ); - assertReportRequestDimension( - requests[6], - ReportRequest.RequestLayout.column, - 3, - 0 - ); - assertReportRequestDimension( - requests[7], - ReportRequest.RequestLayout.column, - 3, - 1 - ); - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 5, 3, 0, 0); - - // 8 sets representant chaque cas (set +, -) sur les 4 types d'association - // ici le cas du BL (sauf 11) n'est traité que par absence de SO - assertResultRow(result, 0, "1", "1", "1", "1", "4"); - assertResultRow(result, 1, "1", "1", "1", "1", "4"); - assertResultRow(result, 2, "2", "2", "2", "2", "8"); - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/targetCatchByAssociation/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/targetCatchByAssociation/ReportIT.java deleted file mode 100644 index d8dc4b0..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/targetCatchByAssociation/ReportIT.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.targetCatchByAssociation; - -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; - -/** - * Test le report {@code targetCatchByAssociation}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class ReportIT extends AbstractReportIT { - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Capture de thon selon le type d'association (en t)", - "Afficher la répartitions des captures de thons selon le type d'association" - ); - - assertReportDimension( - report, - 5, - 7, - new String[]{"YFT", - "SKJ", - "BET", - "LTA", - "FRI", - "Autres", - "Total" - }, - new String[]{"BL sans baleine", - "BL avec baleine", - "BO avec requin-baleine", - "BO sans requin-baleine", - "Total" - } - ); - - assertReportNbRequests(report, 24); - - ReportRequest[] requests = report.getRequests(); - ReportRequest request; - - for (int i = 0; i < 24; i++) { - request = requests[i]; - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - i % 6, - i / 6 - ); - } - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 7, 5, 0, 0); - - assertResultRow(result, 0, "1.0", "2.0", "3.0", "4.0", "5.0", "6.0", "21.0"); - assertResultRow(result, 1, "1.0", "2.0", "3.0", "4.0", "5.0", "6.0", "21.0"); - assertResultRow(result, 2, "1.0", "2.0", "3.0", "4.0", "5.0", "6.0", "21.0"); - assertResultRow(result, 3, "1.0", "2.0", "3.0", "4.0", "5.0", "6.0", "21.0"); - assertResultRow(result, 4, "4.0", "8.0", "12.0", "16.0", "20.0", "24.0", "84.0"); - - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/its/report/targetDiscardedByAssociation/ReportIT.java b/observe-business/src/test/java/fr/ird/observe/its/report/targetDiscardedByAssociation/ReportIT.java deleted file mode 100644 index ad445f1..0000000 --- a/observe-business/src/test/java/fr/ird/observe/its/report/targetDiscardedByAssociation/ReportIT.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.its.report.targetDiscardedByAssociation; - -import fr.ird.observe.its.report.AbstractReportIT; -import fr.ird.observe.report.model.DataMatrix; -import fr.ird.observe.report.model.Report; -import fr.ird.observe.report.model.ReportRequest; -import org.junit.Assert; - -/** - * Test le report {@code targetDiscardedByAssociation}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9 - */ -public class ReportIT extends AbstractReportIT { - - @Override - protected void testReportSyntax(Report report) { - Assert.assertNotNull(report); - assertReportName( - report, - "Rejets de thons selon le type d’association (en t)", - "Afficher la répartitions des rejets de thons selon le type d'association" - ); - - assertReportDimension( - report, - 5, - 7, - new String[]{"YFT", - "SKJ", - "BET", - "LTA", - "FRI", - "Autres", - "Total" - }, - new String[]{"BL sans baleine", - "BL avec baleine", - "BO avec requin-baleine", - "BO sans requin-baleine", - "Total" - } - ); - - assertReportNbRequests(report, 24); - - ReportRequest[] requests = report.getRequests(); - ReportRequest request; - - for (int i = 0; i < 24; i++) { - request = requests[i]; - assertReportRequestDimension( - request, - ReportRequest.RequestLayout.row, - i % 6, - i / 6 - ); - } - } - - @Override - protected void testReportResult(DataMatrix result) { - assertResultDimension(result, 7, 5, 0, 0); - - assertResultRow(result, 0, "6.0", "5.0", "4.0", "3.0", "2.0", "1.0", "21.0"); - assertResultRow(result, 1, "6.0", "5.0", "4.0", "3.0", "2.0", "1.0", "21.0"); - assertResultRow(result, 2, "6.0", "5.0", "4.0", "3.0", "2.0", "1.0", "21.0"); - assertResultRow(result, 3, "6.0", "5.0", "4.0", "3.0", "2.0", "1.0", "21.0"); - assertResultRow(result, 4, "24.0", "20.0", "16.0", "12.0", "8.0", "4.0", "84.0"); - - } -} diff --git a/observe-business/src/test/java/fr/ird/observe/validation/ValidationServiceTest.java b/observe-business/src/test/java/fr/ird/observe/validation/ValidationServiceTest.java deleted file mode 100644 index 3704400..0000000 --- a/observe-business/src/test/java/fr/ird/observe/validation/ValidationServiceTest.java +++ /dev/null @@ -1,517 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.business.validation; - -import fr.ird.observe.entities.referentiel.Country; -import fr.ird.observe.entities.referentiel.Ocean; -import fr.ird.observe.entities.referentiel.OceanImpl; -import fr.ird.observe.entities.referentiel.Program; -import fr.ird.observe.entities.referentiel.ProgramImpl; -import fr.ird.observe.entities.referentiel.Species; -import fr.ird.observe.entities.referentiel.SpeciesImpl; -import fr.ird.observe.entities.referentiel.Vessel; -import fr.ird.observe.entities.referentiel.seine.WeightCategory; -import fr.ird.observe.entities.referentiel.seine.WeightCategoryImpl; -import fr.ird.observe.entities.seine.ActivitySeine; -import fr.ird.observe.entities.seine.ActivitySeineImpl; -import fr.ird.observe.entities.seine.FloatingObject; -import fr.ird.observe.entities.seine.FloatingObjectImpl; -import fr.ird.observe.entities.seine.Route; -import fr.ird.observe.entities.seine.RouteImpl; -import fr.ird.observe.entities.seine.SchoolEstimate; -import fr.ird.observe.entities.seine.SchoolEstimateImpl; -import fr.ird.observe.entities.seine.SetSeine; -import fr.ird.observe.entities.seine.SetSeineImpl; -import fr.ird.observe.entities.seine.TargetCatch; -import fr.ird.observe.entities.seine.TargetCatchImpl; -import fr.ird.observe.entities.seine.TargetLength; -import fr.ird.observe.entities.seine.TargetLengthImpl; -import fr.ird.observe.entities.seine.TargetSample; -import fr.ird.observe.entities.seine.TargetSampleImpl; -import fr.ird.observe.entities.seine.TripSeine; -import fr.ird.observe.entities.seine.TripSeineImpl; -import fr.ird.observe.test.TestHelper; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.TopiaEntityRef; -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.bean.simple.SimpleBeanValidator; -import org.nuiton.validator.bean.simple.SimpleBeanValidatorMessage; - -import java.util.List; -import java.util.SortedMap; - -/** - * Dans ce test on dispose de 3 contexts test1, test2, test3. - * <p/> - * On dispose des validateurs suivants : - * <pre> - * |-- TripSeine-test2-error-validation.xml - * |-- TripSeine-test3-warning-validation.xml - * `-- referentiel - * |-- Ocean-test3-error-validation.xml - * |-- Program-test1-error-validation.xml - * `-- Program-test3-info-validation.xml - * </pre> - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class ValidationServiceTest { - - private static final String CONTEXT_NAME_TEST1 = "test1"; - - private static final String CONTEXT_NAME_TEST2 = "test2"; - - private static final String CONTEXT_NAME_TEST3 = "test3"; - - protected ValidationService service; - - SimpleBeanValidator<?> validator; - - ValidatorsMap validators; - - protected SortedMap<TopiaEntityRef, List<SimpleBeanValidatorMessage<?>>> messages; - - static protected Program program; - - static protected Country country; - - static protected Route route; - - static protected TripSeine maree; - - static protected ActivitySeine activitySeine; - - static protected SetSeine setSeine; - - static protected FloatingObject dcp; - - static protected SchoolEstimate estimation; - - static protected Species species; - - static protected WeightCategory weightCategory; - - static protected TargetCatch discarded; - - static protected TargetLength taille; - - static protected TargetSample echantillon; - - static protected Vessel vessel; - - static protected Ocean ocean; - - - @BeforeClass - public static void beforeClass() { - - - TestHelper.initTest(ValidationServiceTest.class); - - TestHelper.createApplicationContext(); - - program = new ProgramImpl(); - program.setTopiaId("Program1"); - - maree = new TripSeineImpl(); - maree.setTopiaId("Trip1"); - - ocean = new OceanImpl(); - ocean.setTopiaId("Ocean1"); - - species = new SpeciesImpl(); - species.setTopiaId("speciesThon"); - weightCategory = new WeightCategoryImpl(); - weightCategory.setTopiaId("weightCategory"); - weightCategory.setSpecies(species); - - echantillon = new TargetSampleImpl(); - echantillon.setTopiaId("echantillon"); - - taille = new TargetLengthImpl(); - taille.setTopiaId("targetLength"); - taille.setTargetSample(echantillon); - taille.setSpecies(species); - taille.setCount(1); - - route = new RouteImpl(); - route.setTopiaId("route"); - activitySeine = new ActivitySeineImpl(); - activitySeine.setTopiaId("activity"); - - setSeine = new SetSeineImpl(); - setSeine.setTopiaId("set"); - - dcp = new FloatingObjectImpl(); - dcp.setTopiaId("dcp"); - - discarded = new TargetCatchImpl(); - discarded.setTopiaId("targetCatche"); - - discarded.setSetSeine(setSeine); - discarded.setWeightCategory(weightCategory); - discarded.setCatchWeight(1.0f); - - estimation = new SchoolEstimateImpl(); - estimation.setTopiaId("schoolSizeEstimation"); - estimation.setSetSeine(setSeine); - estimation.setSpecies(species); - estimation.setTotalWeight(10); - - maree.setProgram(program); - maree.setOcean(ocean); - maree.addRoute(route); - - route.addActivitySeine(activitySeine); - activitySeine.addFloatingObject(dcp); - activitySeine.setSetSeine(setSeine); - echantillon.addTargetLength(taille); - setSeine.addTargetSample(echantillon); - setSeine.addTargetCatch(discarded); - } - - @Before - public void setUp() throws Exception { - service = new ValidationService(); - } - - @After - public void tearDown() throws Exception { - service = null; - validator = null; - validators = null; - messages = null; - } - - @Test - public void testGetProgramValidator() throws Exception { - - validator = service.getValidator(CONTEXT_NAME_TEST1, - null, - Program.class - ); - - assertBeanValidator(CONTEXT_NAME_TEST1, NuitonValidatorScope.ERROR); - - validator = service.getValidator(CONTEXT_NAME_TEST2, - null, - Program.class - ); - - assertBeanValidator(null); - - validator = service.getValidator(CONTEXT_NAME_TEST3, - null, - Program.class - ); - - assertBeanValidator(CONTEXT_NAME_TEST3, NuitonValidatorScope.INFO); - } - - @Test - public void testGetTripValidator() throws Exception { - - validator = service.getValidator(CONTEXT_NAME_TEST1, - null, - TripSeine.class - ); - - assertBeanValidator(null); - - validator = service.getValidator(CONTEXT_NAME_TEST2, - null, - TripSeine.class - ); - - assertBeanValidator(CONTEXT_NAME_TEST2, NuitonValidatorScope.ERROR); - - validator = service.getValidator(CONTEXT_NAME_TEST3, - null, - TripSeine.class - ); - - assertBeanValidator(CONTEXT_NAME_TEST3, NuitonValidatorScope.WARNING); - - } - - - @Test - public void testGetOceanValidator() throws Exception { - - validator = service.getValidator(CONTEXT_NAME_TEST1, - null, - Ocean.class); - - assertBeanValidator(null); - - validator = service.getValidator(CONTEXT_NAME_TEST2, - null, - Ocean.class - ); - - assertBeanValidator(null); - - validator = service.getValidator(CONTEXT_NAME_TEST3, - null, - Ocean.class - ); - - assertBeanValidator(CONTEXT_NAME_TEST3, NuitonValidatorScope.ERROR); - } - - - @Test - public void testGetValidators() throws Exception { - - validators = service.getValidators(CONTEXT_NAME_TEST1, - null, - Program.class, - TripSeine.class - ); - - // sur ce context, seul le program a un validateur - assertValidators(Program.class); - - validators = service.getValidators(CONTEXT_NAME_TEST2, - null, - Program.class, - TripSeine.class - ); - - // sur ce context, seul la maree a un validateur - assertValidators(TripSeine.class); - - validators = service.getValidators(CONTEXT_NAME_TEST3, - null, - Program.class, - TripSeine.class, - Ocean.class - ); - - // sur ce context, tout est a valider - assertValidators(Program.class, TripSeine.class, Ocean.class); - - - // filtre sur le scope error uniquement - - validators = service.getValidators( - CONTEXT_NAME_TEST3, - new NuitonValidatorScope[]{NuitonValidatorScope.ERROR}, - Program.class, - TripSeine.class, - Ocean.class - ); - - assertValidators(Ocean.class); - - // filtre sur le scope warning uniquement - - validators = service.getValidators( - CONTEXT_NAME_TEST3, - new NuitonValidatorScope[]{NuitonValidatorScope.WARNING}, - Program.class, - TripSeine.class, - Ocean.class - ); - - assertValidators(TripSeine.class); - - // filtre sur le scope info uniquement - - validators = service.getValidators( - CONTEXT_NAME_TEST3, - new NuitonValidatorScope[]{NuitonValidatorScope.INFO}, - Program.class, - TripSeine.class, - Ocean.class - ); - - assertValidators(Program.class); - - // filtre sur le scope error warning uniquement - - validators = service.getValidators( - CONTEXT_NAME_TEST3, - new NuitonValidatorScope[]{ - NuitonValidatorScope.WARNING, - NuitonValidatorScope.ERROR - }, - Program.class, - TripSeine.class, - Ocean.class - ); - - assertValidators(TripSeine.class, Ocean.class); - } - - //TODO A refaire en utilisant le ValidationMessageDetector - -// @Test -// public void testDetectMessages1() throws Exception { -// -// String contextName = "test1"; -// -// // recuperation des validateurs pour ce context et ces entites -// validators = service.getValidators(contextName, null, program, maree); -// -// // sur ce context, seul le program a un validateur -// assertValidators(Program.class); -// -// // detection des messages de validations -// messages = service.detectMessages(validators, maree); -// -// // on valide uniquement le fait que le program a un code <1 -// -// Assert.assertNotNull(messages); -// Assert.assertEquals(1, messages.size()); -// TopiaEntityRef ref = messages.keySet().iterator().next(); -// Assert.assertEquals(program, ref.getRef()); -// List<BeanValidatorMessage<?>> validatorMessages = messages.get(ref); -// Assert.assertNotNull(validatorMessages); -// Assert.assertEquals(1, validatorMessages.size()); -// BeanValidatorMessage<?> message = validatorMessages.get(0); -// assertMessage(message, ref.getRef(), program, Program.PROPERTY_CODE, NuitonValidatorScope.ERROR); -// } -// -// @Test -// public void testDetectMessages2() throws Exception { -// -// -// String contextName = "test2"; -// -// // recuperation des validateurs pour ce context et ces entites -// validators = service.getValidators(contextName, null, program, maree); -// -// // sur ce context, seul la maree a un validateur -// assertValidators(Trip.class); -// -// // detection des messages de validations -// messages = service.detectMessages(validators, maree); -// -// // on valide uniquement le fait que la maree n'a pas de vessel -// -// Assert.assertNotNull(messages); -// Assert.assertEquals(1, messages.size()); -// TopiaEntityRef ref = messages.keySet().iterator().next(); -// Assert.assertEquals(maree, ref.getRef()); -// List<BeanValidatorMessage<?>> validatorMessages = messages.get(ref); -// Assert.assertNotNull(validatorMessages); -// Assert.assertEquals(1, validatorMessages.size()); -// BeanValidatorMessage<?> message = validatorMessages.get(0); -// assertMessage(message, ref.getRef(), maree, "vessel", NuitonValidatorScope.ERROR); -// } -// -// @Test -// public void testDetectMessages3() throws Exception { -// -// String contextName = "test3"; -// -// // recuperation des validateurs pour ce context et ces entites -// validators = service.getValidators(contextName, null, maree, ocean); -// -// // sur ce context, tout est a valider -// assertValidators(Program.class, Trip.class, Ocean.class); -// -// // detection des messages de validations -// messages = service.detectMessages(validators, maree); -// -// Assert.assertNotNull(messages); -// Assert.assertEquals(3, messages.size()); -// -// TopiaEntityRef ref; -// List<BeanValidatorMessage<?>> validatorMessages; -// BeanValidatorMessage<?> message; -// -// Iterator<TopiaEntityRef> iterator = messages.keySet().iterator(); -// ref = iterator.next(); -// Assert.assertEquals(maree, ref.getRef()); -// validatorMessages = messages.get(ref); -// Assert.assertNotNull(validatorMessages); -// Assert.assertEquals(1, validatorMessages.size()); -// message = validatorMessages.get(0); -// assertMessage(message, ref.getRef(), maree, "vessel", NuitonValidatorScope.WARNING); -// -// ref = iterator.next(); -// Assert.assertEquals(ocean, ref.getRef()); -// validatorMessages = messages.get(ref); -// Assert.assertNotNull(validatorMessages); -// Assert.assertEquals(1, validatorMessages.size()); -// message = validatorMessages.get(0); -// assertMessage(message, ref.getRef(), ocean, "code", NuitonValidatorScope.ERROR); -// -// ref = iterator.next(); -// Assert.assertEquals(program, ref.getRef()); -// validatorMessages = messages.get(ref); -// Assert.assertNotNull(validatorMessages); -// Assert.assertEquals(1, validatorMessages.size()); -// message = validatorMessages.get(0); -// assertMessage(message, ref.getRef(), program, "code", NuitonValidatorScope.INFO); -// } - - protected void assertBeanValidator(String contextName, - NuitonValidatorScope... scopes) { - - if (contextName == null) { - - // pas de validateur - Assert.assertNull(validator); - return; - } - - Assert.assertNotNull(validator); - - Assert.assertEquals(contextName, validator.getContext()); - - int length = scopes.length; - Assert.assertEquals(length, validator.getEffectiveScopes().size()); - for (int i = 0; i < length; i++) { - - NuitonValidatorScope scope = scopes[i]; - Assert.assertTrue(validator.getScopes().contains(scope)); - } - } - - protected void assertValidators( - Class<?>... expected) { - Assert.assertEquals(expected.length, validators.size()); - java.util.Set<?> classSet = validators.keySet(); - for (Class<?> c : expected) { - Assert.assertTrue(classSet.contains(c)); - } - } - - protected void assertMessage(SimpleBeanValidatorMessage<?> message, - TopiaEntity entity, - TopiaEntity exceptedEntity, - String expectedCode, - NuitonValidatorScope exceptedScope) { - Assert.assertEquals(exceptedScope, message.getScope()); - Assert.assertEquals(exceptedEntity, entity); - Assert.assertEquals(expectedCode, message.getField()); - } - -} diff --git a/observe-business/src/test/resources/db/4.0.2/referentiel.sql.gz b/observe-business/src/test/resources/db/4.0.2/referentiel.sql.gz deleted file mode 100644 index 1447432..0000000 Binary files a/observe-business/src/test/resources/db/4.0.2/referentiel.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Ocean-test3-error-validation.xml b/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Ocean-test3-error-validation.xml deleted file mode 100644 index 7d87c61..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Ocean-test3-error-validation.xml +++ /dev/null @@ -1,32 +0,0 @@ -<!-- - #%L - ObServe :: Business - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!DOCTYPE validators PUBLIC - "-//Apache Struts//XWork Validator 1.0.3//EN" - "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> -<validators> - <field name="code"> - <field-validator type="int" short-circuit="true"> - <param name="min">1</param> - <message>validator.program.positive.code</message> - </field-validator> - </field> -</validators> diff --git a/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Program-test1-error-validation.xml b/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Program-test1-error-validation.xml deleted file mode 100644 index 7d87c61..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Program-test1-error-validation.xml +++ /dev/null @@ -1,32 +0,0 @@ -<!-- - #%L - ObServe :: Business - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!DOCTYPE validators PUBLIC - "-//Apache Struts//XWork Validator 1.0.3//EN" - "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> -<validators> - <field name="code"> - <field-validator type="int" short-circuit="true"> - <param name="min">1</param> - <message>validator.program.positive.code</message> - </field-validator> - </field> -</validators> diff --git a/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Program-test3-info-validation.xml b/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Program-test3-info-validation.xml deleted file mode 100644 index 7d87c61..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/entities/referentiel/Program-test3-info-validation.xml +++ /dev/null @@ -1,32 +0,0 @@ -<!-- - #%L - ObServe :: Business - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!DOCTYPE validators PUBLIC - "-//Apache Struts//XWork Validator 1.0.3//EN" - "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> -<validators> - <field name="code"> - <field-validator type="int" short-circuit="true"> - <param name="min">1</param> - <message>validator.program.positive.code</message> - </field-validator> - </field> -</validators> diff --git a/observe-business/src/test/resources/fr/ird/observe/entities/seine/TripSeine-test2-error-validation.xml b/observe-business/src/test/resources/fr/ird/observe/entities/seine/TripSeine-test2-error-validation.xml deleted file mode 100644 index 203bd1a..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/entities/seine/TripSeine-test2-error-validation.xml +++ /dev/null @@ -1,31 +0,0 @@ -<!-- - #%L - ObServe :: Business - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!DOCTYPE validators PUBLIC - "-//Apache Struts//XWork Validator 1.0.3//EN" - "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> -<validators> - <field name="vessel"> - <field-validator type="required" short-circuit="true"> - <message>validator.activity.required.time</message> - </field-validator> - </field> -</validators> diff --git a/observe-business/src/test/resources/fr/ird/observe/entities/seine/TripSeine-test3-warning-validation.xml b/observe-business/src/test/resources/fr/ird/observe/entities/seine/TripSeine-test3-warning-validation.xml deleted file mode 100644 index 203bd1a..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/entities/seine/TripSeine-test3-warning-validation.xml +++ /dev/null @@ -1,31 +0,0 @@ -<!-- - #%L - ObServe :: Business - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!DOCTYPE validators PUBLIC - "-//Apache Struts//XWork Validator 1.0.3//EN" - "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> -<validators> - <field name="vessel"> - <field-validator type="required" short-circuit="true"> - <message>validator.activity.required.time</message> - </field-validator> - </field> -</validators> diff --git a/observe-business/src/test/resources/fr/ird/observe/gps/GL50_13_small.gpx b/observe-business/src/test/resources/fr/ird/observe/gps/GL50_13_small.gpx deleted file mode 100644 index a2a69a7..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/gps/GL50_13_small.gpx +++ /dev/null @@ -1,167 +0,0 @@ -<?xml version="1.0"?> -<gpx -version="1.0" -creator="LOG Converter 1.51" -xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xmlns="http://www.topografix.com/GPX/1/0" -xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/2" -xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/2 http://www.topografix.com/GPX/Private/TopoGrafix/0/2/topografix.xsd"> - <time>2008-10-09T17:09:22</time> - <bounds minlat="-9.158406" minlon="49.513565" maxlat="-3.977783" maxlon="59.126060"/> - <trk> - <name>exemple_GL50_13_corrige</name> - <trkseg> - <trkpt lat="-4.621102" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T03:54:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621067" lon="55.461028"> - <ele>0.000000</ele> - <time>2007-11-09T03:59:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621072" lon="55.461065"> - <ele>0.000000</ele> - <time>2007-11-09T04:04:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.620885" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T04:09:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621702" lon="55.462778"> - <ele>0.000000</ele> - <time>2007-11-09T04:14:27.000Z</time> - <course>0.000000</course> - <speed>0.463000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.619307" lon="55.465857"> - <ele>0.000000</ele> - <time>2007-11-09T04:19:27.000Z</time> - <course>44.209999</course> - <speed>1.563911</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.614558" lon="55.471957"> - <ele>0.000000</ele> - <time>2007-11-09T04:24:27.000Z</time> - <course>65.889999</course> - <speed>4.377922</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.609248" lon="55.483448"> - <ele>0.000000</ele> - <time>2007-11-09T04:29:27.000Z</time> - <course>57.099998</course> - <speed>4.774044</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600630" lon="55.489975"> - <ele>0.000000</ele> - <time>2007-11-09T04:34:27.000Z</time> - <course>355.049988</course> - <speed>3.225567</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600225" lon="55.489840"> - <ele>0.000000</ele> - <time>2007-11-09T04:39:27.000Z</time> - <course>339.739990</course> - <speed>0.149189</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600133" lon="55.489788"> - <ele>0.000000</ele> - <time>2007-11-09T04:44:27.000Z</time> - <course>339.739990</course> - <speed>0.113178</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600182" lon="55.489875"> - <ele>0.000000</ele> - <time>2007-11-09T04:49:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600155" lon="55.489867"> - <ele>0.000000</ele> - <time>2007-11-09T04:54:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600117" lon="55.489877"> - <ele>0.000000</ele> - <time>2007-11-09T04:59:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - - <trkpt lat="-3.977783" lon="51.929418"> - <ele>0.000000</ele> - <time>2007-11-29T10:32:48.000Z</time> - <course>282.089996</course> - <speed>6.353389</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - </trkseg> - </trk> -</gpx> diff --git a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_allAccepted.gpx b/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_allAccepted.gpx deleted file mode 100644 index 7933c7b..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_allAccepted.gpx +++ /dev/null @@ -1,157 +0,0 @@ -<?xml version="1.0"?> -<gpx -version="1.0" -creator="LOG Converter 1.51" -xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xmlns="http://www.topografix.com/GPX/1/0" -xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/2" -xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/2 http://www.topografix.com/GPX/Private/TopoGrafix/0/2/topografix.xsd"> - <time>2008-10-09T17:09:22</time> - <bounds minlat="-9.158406" minlon="49.513565" maxlat="-3.977783" maxlon="59.126060"/> - <trk> - <name>exemple_GL50_13_corrige</name> - <trkseg> - <trkpt lat="-4.621102" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T03:54:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621067" lon="55.461028"> - <ele>0.000000</ele> - <time>2007-11-09T03:59:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621072" lon="55.461065"> - <ele>0.000000</ele> - <time>2007-11-09T04:04:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.620885" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T04:09:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621702" lon="55.462778"> - <ele>0.000000</ele> - <time>2007-11-09T04:14:27.000Z</time> - <course>0.000000</course> - <speed>0.463000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.619307" lon="55.465857"> - <ele>0.000000</ele> - <time>2007-11-09T04:19:27.000Z</time> - <course>44.209999</course> - <speed>1.563911</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.614558" lon="55.471957"> - <ele>0.000000</ele> - <time>2007-11-09T04:24:27.000Z</time> - <course>65.889999</course> - <speed>4.377922</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.609248" lon="55.483448"> - <ele>0.000000</ele> - <time>2007-11-09T04:29:27.000Z</time> - <course>57.099998</course> - <speed>4.774044</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600630" lon="55.489975"> - <ele>0.000000</ele> - <time>2007-11-09T04:34:27.000Z</time> - <course>355.049988</course> - <speed>3.225567</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600225" lon="55.489840"> - <ele>0.000000</ele> - <time>2007-11-09T04:39:27.000Z</time> - <course>339.739990</course> - <speed>0.149189</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600133" lon="55.489788"> - <ele>0.000000</ele> - <time>2007-11-09T04:44:27.000Z</time> - <course>339.739990</course> - <speed>0.113178</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600182" lon="55.489875"> - <ele>0.000000</ele> - <time>2007-11-09T04:49:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600155" lon="55.489867"> - <ele>0.000000</ele> - <time>2007-11-09T04:54:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600117" lon="55.489877"> - <ele>0.000000</ele> - <time>2007-11-09T04:59:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - - </trkseg> - </trk> -</gpx> diff --git a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_allRejected.gpx b/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_allRejected.gpx deleted file mode 100644 index 7933c7b..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_allRejected.gpx +++ /dev/null @@ -1,157 +0,0 @@ -<?xml version="1.0"?> -<gpx -version="1.0" -creator="LOG Converter 1.51" -xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xmlns="http://www.topografix.com/GPX/1/0" -xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/2" -xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/2 http://www.topografix.com/GPX/Private/TopoGrafix/0/2/topografix.xsd"> - <time>2008-10-09T17:09:22</time> - <bounds minlat="-9.158406" minlon="49.513565" maxlat="-3.977783" maxlon="59.126060"/> - <trk> - <name>exemple_GL50_13_corrige</name> - <trkseg> - <trkpt lat="-4.621102" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T03:54:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621067" lon="55.461028"> - <ele>0.000000</ele> - <time>2007-11-09T03:59:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621072" lon="55.461065"> - <ele>0.000000</ele> - <time>2007-11-09T04:04:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.620885" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T04:09:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621702" lon="55.462778"> - <ele>0.000000</ele> - <time>2007-11-09T04:14:27.000Z</time> - <course>0.000000</course> - <speed>0.463000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.619307" lon="55.465857"> - <ele>0.000000</ele> - <time>2007-11-09T04:19:27.000Z</time> - <course>44.209999</course> - <speed>1.563911</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.614558" lon="55.471957"> - <ele>0.000000</ele> - <time>2007-11-09T04:24:27.000Z</time> - <course>65.889999</course> - <speed>4.377922</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.609248" lon="55.483448"> - <ele>0.000000</ele> - <time>2007-11-09T04:29:27.000Z</time> - <course>57.099998</course> - <speed>4.774044</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600630" lon="55.489975"> - <ele>0.000000</ele> - <time>2007-11-09T04:34:27.000Z</time> - <course>355.049988</course> - <speed>3.225567</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600225" lon="55.489840"> - <ele>0.000000</ele> - <time>2007-11-09T04:39:27.000Z</time> - <course>339.739990</course> - <speed>0.149189</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600133" lon="55.489788"> - <ele>0.000000</ele> - <time>2007-11-09T04:44:27.000Z</time> - <course>339.739990</course> - <speed>0.113178</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600182" lon="55.489875"> - <ele>0.000000</ele> - <time>2007-11-09T04:49:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600155" lon="55.489867"> - <ele>0.000000</ele> - <time>2007-11-09T04:54:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600117" lon="55.489877"> - <ele>0.000000</ele> - <time>2007-11-09T04:59:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - - </trkseg> - </trk> -</gpx> diff --git a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_firtPointsRejected.gpx b/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_firtPointsRejected.gpx deleted file mode 100644 index 5cc60bc..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_firtPointsRejected.gpx +++ /dev/null @@ -1,157 +0,0 @@ -<?xml version="1.0"?> -<gpx -version="1.0" -creator="LOG Converter 1.51" -xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xmlns="http://www.topografix.com/GPX/1/0" -xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/2" -xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/2 http://www.topografix.com/GPX/Private/TopoGrafix/0/2/topografix.xsd"> - <time>2008-10-09T17:09:22</time> - <bounds minlat="-9.158406" minlon="49.513565" maxlat="-3.977783" maxlon="59.126060"/> - <trk> - <name>exemple_GL50_13_corrige</name> - <trkseg> - <trkpt lat="-4.621102" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T03:48:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621067" lon="55.461028"> - <ele>0.000000</ele> - <time>2007-11-09T03:59:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621072" lon="55.461065"> - <ele>0.000000</ele> - <time>2007-11-09T04:04:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.620885" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T04:09:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621702" lon="55.462778"> - <ele>0.000000</ele> - <time>2007-11-09T04:14:27.000Z</time> - <course>0.000000</course> - <speed>0.463000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.619307" lon="55.465857"> - <ele>0.000000</ele> - <time>2007-11-09T04:19:27.000Z</time> - <course>44.209999</course> - <speed>1.563911</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.614558" lon="55.471957"> - <ele>0.000000</ele> - <time>2007-11-09T04:24:27.000Z</time> - <course>65.889999</course> - <speed>4.377922</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.609248" lon="55.483448"> - <ele>0.000000</ele> - <time>2007-11-09T04:29:27.000Z</time> - <course>57.099998</course> - <speed>4.774044</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600630" lon="55.489975"> - <ele>0.000000</ele> - <time>2007-11-09T04:34:27.000Z</time> - <course>355.049988</course> - <speed>3.225567</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600225" lon="55.489840"> - <ele>0.000000</ele> - <time>2007-11-09T04:39:27.000Z</time> - <course>339.739990</course> - <speed>0.149189</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600133" lon="55.489788"> - <ele>0.000000</ele> - <time>2007-11-09T04:44:27.000Z</time> - <course>339.739990</course> - <speed>0.113178</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600182" lon="55.489875"> - <ele>0.000000</ele> - <time>2007-11-09T04:49:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600155" lon="55.489867"> - <ele>0.000000</ele> - <time>2007-11-09T04:54:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600117" lon="55.489877"> - <ele>0.000000</ele> - <time>2007-11-09T04:59:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - - </trkseg> - </trk> -</gpx> diff --git a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_insidePointsRejected.gpx b/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_insidePointsRejected.gpx deleted file mode 100644 index c8cd501..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_insidePointsRejected.gpx +++ /dev/null @@ -1,157 +0,0 @@ -<?xml version="1.0"?> -<gpx -version="1.0" -creator="LOG Converter 1.51" -xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xmlns="http://www.topografix.com/GPX/1/0" -xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/2" -xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/2 http://www.topografix.com/GPX/Private/TopoGrafix/0/2/topografix.xsd"> - <time>2008-10-09T17:09:22</time> - <bounds minlat="-9.158406" minlon="49.513565" maxlat="-3.977783" maxlon="59.126060"/> - <trk> - <name>exemple_GL50_13_corrige</name> - <trkseg> - <trkpt lat="-4.621102" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T03:54:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621067" lon="55.461028"> - <ele>0.000000</ele> - <time>2007-11-09T03:59:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621072" lon="55.461065"> - <ele>0.000000</ele> - <time>2007-11-09T04:06:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.620885" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T04:09:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621702" lon="55.462778"> - <ele>0.000000</ele> - <time>2007-11-09T04:14:26.000Z</time> - <course>0.000000</course> - <speed>0.463000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.619307" lon="55.465857"> - <ele>0.000000</ele> - <time>2007-11-09T04:19:26.000Z</time> - <course>44.209999</course> - <speed>1.563911</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.614558" lon="55.471957"> - <ele>0.000000</ele> - <time>2007-11-09T04:24:26.000Z</time> - <course>65.889999</course> - <speed>4.377922</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.609248" lon="55.483448"> - <ele>0.000000</ele> - <time>2007-11-09T04:29:26.000Z</time> - <course>57.099998</course> - <speed>4.774044</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600630" lon="55.489975"> - <ele>0.000000</ele> - <time>2007-11-09T04:34:26.000Z</time> - <course>355.049988</course> - <speed>3.225567</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600225" lon="55.489840"> - <ele>0.000000</ele> - <time>2007-11-09T04:39:26.000Z</time> - <course>339.739990</course> - <speed>0.149189</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600133" lon="55.489788"> - <ele>0.000000</ele> - <time>2007-11-09T04:44:26.000Z</time> - <course>339.739990</course> - <speed>0.113178</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600182" lon="55.489875"> - <ele>0.000000</ele> - <time>2007-11-09T04:49:26.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600155" lon="55.489867"> - <ele>0.000000</ele> - <time>2007-11-09T04:54:26.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600117" lon="55.489877"> - <ele>0.000000</ele> - <time>2007-11-09T04:59:26.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - - </trkseg> - </trk> -</gpx> diff --git a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_insidePointsRejected2.gpx b/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_insidePointsRejected2.gpx deleted file mode 100644 index 5523561..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_insidePointsRejected2.gpx +++ /dev/null @@ -1,157 +0,0 @@ -<?xml version="1.0"?> -<gpx -version="1.0" -creator="LOG Converter 1.51" -xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xmlns="http://www.topografix.com/GPX/1/0" -xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/2" -xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/2 http://www.topografix.com/GPX/Private/TopoGrafix/0/2/topografix.xsd"> - <time>2008-10-09T17:09:22</time> - <bounds minlat="-9.158406" minlon="49.513565" maxlat="-3.977783" maxlon="59.126060"/> - <trk> - <name>exemple_GL50_13_corrige</name> - <trkseg> - <trkpt lat="-4.621102" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T03:54:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621067" lon="55.461028"> - <ele>0.000000</ele> - <time>2007-11-09T03:59:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621072" lon="55.461065"> - <ele>0.000000</ele> - <time>2007-11-09T04:06:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.620885" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T04:09:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621702" lon="55.462778"> - <ele>0.000000</ele> - <time>2007-11-09T04:14:26.000Z</time> - <course>0.000000</course> - <speed>0.463000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.619307" lon="55.465857"> - <ele>0.000000</ele> - <time>2007-11-09T04:19:26.000Z</time> - <course>44.209999</course> - <speed>1.563911</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.614558" lon="55.471957"> - <ele>0.000000</ele> - <time>2007-11-09T04:24:26.000Z</time> - <course>65.889999</course> - <speed>4.377922</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.609248" lon="55.483448"> - <ele>0.000000</ele> - <time>2007-11-09T04:29:26.000Z</time> - <course>57.099998</course> - <speed>4.774044</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600630" lon="55.489975"> - <ele>0.000000</ele> - <time>2007-11-09T04:34:26.000Z</time> - <course>355.049988</course> - <speed>3.225567</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600225" lon="55.489840"> - <ele>0.000000</ele> - <time>2007-11-09T04:39:26.000Z</time> - <course>339.739990</course> - <speed>0.149189</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600133" lon="55.489788"> - <ele>0.000000</ele> - <time>2007-11-09T04:44:26.000Z</time> - <course>339.739990</course> - <speed>0.113178</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600182" lon="55.489875"> - <ele>0.000000</ele> - <time>2007-11-09T04:50:26.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600155" lon="55.489867"> - <ele>0.000000</ele> - <time>2007-11-09T04:56:26.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600117" lon="55.489877"> - <ele>0.000000</ele> - <time>2007-11-09T04:59:26.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - - </trkseg> - </trk> -</gpx> diff --git a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_lastPointsRejected.gpx b/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_lastPointsRejected.gpx deleted file mode 100644 index a9a6342..0000000 --- a/observe-business/src/test/resources/fr/ird/observe/gps/testInterval_lastPointsRejected.gpx +++ /dev/null @@ -1,157 +0,0 @@ -<?xml version="1.0"?> -<gpx -version="1.0" -creator="LOG Converter 1.51" -xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xmlns="http://www.topografix.com/GPX/1/0" -xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/2" -xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/2 http://www.topografix.com/GPX/Private/TopoGrafix/0/2/topografix.xsd"> - <time>2008-10-09T17:09:22</time> - <bounds minlat="-9.158406" minlon="49.513565" maxlat="-3.977783" maxlon="59.126060"/> - <trk> - <name>exemple_GL50_13_corrige</name> - <trkseg> - <trkpt lat="-4.621102" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T03:54:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621067" lon="55.461028"> - <ele>0.000000</ele> - <time>2007-11-09T03:59:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621072" lon="55.461065"> - <ele>0.000000</ele> - <time>2007-11-09T04:04:26.000Z</time> - <course>0.000000</course> - <speed>0.000000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.620885" lon="55.461163"> - <ele>0.000000</ele> - <time>2007-11-09T04:09:26.000Z</time> - <course>0.000000</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.621702" lon="55.462778"> - <ele>0.000000</ele> - <time>2007-11-09T04:14:27.000Z</time> - <course>0.000000</course> - <speed>0.463000</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.619307" lon="55.465857"> - <ele>0.000000</ele> - <time>2007-11-09T04:19:27.000Z</time> - <course>44.209999</course> - <speed>1.563911</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.614558" lon="55.471957"> - <ele>0.000000</ele> - <time>2007-11-09T04:24:27.000Z</time> - <course>65.889999</course> - <speed>4.377922</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.609248" lon="55.483448"> - <ele>0.000000</ele> - <time>2007-11-09T04:29:27.000Z</time> - <course>57.099998</course> - <speed>4.774044</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600630" lon="55.489975"> - <ele>0.000000</ele> - <time>2007-11-09T04:34:27.000Z</time> - <course>355.049988</course> - <speed>3.225567</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600225" lon="55.489840"> - <ele>0.000000</ele> - <time>2007-11-09T04:39:27.000Z</time> - <course>339.739990</course> - <speed>0.149189</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600133" lon="55.489788"> - <ele>0.000000</ele> - <time>2007-11-09T04:44:27.000Z</time> - <course>339.739990</course> - <speed>0.113178</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600182" lon="55.489875"> - <ele>0.000000</ele> - <time>2007-11-09T04:49:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600155" lon="55.489867"> - <ele>0.000000</ele> - <time>2007-11-09T04:54:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - <trkpt lat="-4.600117" lon="55.489877"> - <ele>0.000000</ele> - <time>2007-11-09T05:59:27.000Z</time> - <course>339.739990</course> - <speed>0.005144</speed> - <sat>0</sat> - <hdop>0.000000</hdop> - <vdop>0.000000</vdop> - <pdop>0.000000</pdop> - </trkpt> - - </trkseg> - </trk> -</gpx> diff --git a/observe-business/src/test/resources/log4j.properties b/observe-business/src/test/resources/log4j.properties deleted file mode 100644 index f61c9dc..0000000 --- a/observe-business/src/test/resources/log4j.properties +++ /dev/null @@ -1,33 +0,0 @@ -### -# #%L -# ObServe :: Business -# %% -# Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit -# %% -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/gpl-3.0.html>. -# #L% -### - -# Global logging configuration -log4j.rootLogger=ERROR, stdout -# Console output... -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%c:%L) %M - %m%n - -# package level -log4j.logger.fr.ird.observe=INFO -log4j.logger.org.nuiton.topia=INFO -log4j.logger.jaxx.runtime.decorator=INFO diff --git a/observe-business/src/test/resources/reports/accessoryCatchByGroup.sql.gz b/observe-business/src/test/resources/reports/accessoryCatchByGroup.sql.gz deleted file mode 100644 index 80336d1..0000000 Binary files a/observe-business/src/test/resources/reports/accessoryCatchByGroup.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/reports/activityWithComment.sql.gz b/observe-business/src/test/resources/reports/activityWithComment.sql.gz deleted file mode 100644 index 5e807b0..0000000 Binary files a/observe-business/src/test/resources/reports/activityWithComment.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/reports/allActivitys.sql.gz b/observe-business/src/test/resources/reports/allActivitys.sql.gz deleted file mode 100644 index 5e807b0..0000000 Binary files a/observe-business/src/test/resources/reports/allActivitys.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/reports/dailySetAndCatch.sql.gz b/observe-business/src/test/resources/reports/dailySetAndCatch.sql.gz deleted file mode 100644 index 0c62964..0000000 Binary files a/observe-business/src/test/resources/reports/dailySetAndCatch.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/reports/dcpUsage.sql.gz b/observe-business/src/test/resources/reports/dcpUsage.sql.gz deleted file mode 100644 index 4fe70af..0000000 Binary files a/observe-business/src/test/resources/reports/dcpUsage.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/reports/setByAssociation.sql.gz b/observe-business/src/test/resources/reports/setByAssociation.sql.gz deleted file mode 100644 index 604c088..0000000 Binary files a/observe-business/src/test/resources/reports/setByAssociation.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/reports/setByAssociation2.sql.gz b/observe-business/src/test/resources/reports/setByAssociation2.sql.gz deleted file mode 100644 index 03a000f..0000000 Binary files a/observe-business/src/test/resources/reports/setByAssociation2.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/reports/targetCatchByAssociation.sql.gz b/observe-business/src/test/resources/reports/targetCatchByAssociation.sql.gz deleted file mode 100644 index 25df307..0000000 Binary files a/observe-business/src/test/resources/reports/targetCatchByAssociation.sql.gz and /dev/null differ diff --git a/observe-business/src/test/resources/reports/targetDiscardedByAssociation.sql.gz b/observe-business/src/test/resources/reports/targetDiscardedByAssociation.sql.gz deleted file mode 100644 index 5f994fe..0000000 Binary files a/observe-business/src/test/resources/reports/targetDiscardedByAssociation.sql.gz and /dev/null differ -- To stop receiving notification emails like this one, please contact codelutin.com SCM administrator <admin+scm@codelutin.com>.
participants (1)
-
codelutin.com scm