Tutti-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- 4058 discussions
Author: tchemit
Date: 2013-02-15 11:03:34 +0100 (Fri, 15 Feb 2013)
New Revision: 419
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/419
Log:
use last release of adagio
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-02-14 23:59:54 UTC (rev 418)
+++ trunk/pom.xml 2013-02-15 10:03:34 UTC (rev 419)
@@ -138,7 +138,7 @@
<slf4jVersion>1.7.2</slf4jVersion>
- <adagioVersion>3.3.2-SNAPSHOT</adagioVersion>
+ <adagioVersion>3.3.2</adagioVersion>
<msaccessImporterVersion>1.4.1</msaccessImporterVersion>
1
0
See <http://ci.nuiton.org/jenkins/job/tutti/342/changes>
Changes:
[blavenier] Fix :
- saveBatchFrequencies now delete extra batch
- store weights for 'inert' and 'livingNotSorted'
Add :
- ReferentialPersistenceService.getSampleCategoryIds()
Improve :
- Merge CatchBatchPersistenceService and SpeciesBatchPersistenceService into BatchPersistenceService
- batch management now use adagio implementation CatchBatchExtendDao
------------------------------------------
[...truncated 79 lines...]
Downloading: http://nexus.nuiton.org/nexus/content/groups/tutti-group/fr/ifremer/adagio/…
Downloading: http://nexus.nuiton.org/nexus/content/groups/public/fr/ifremer/adagio/adagi…
Downloaded: http://nexus.nuiton.org/nexus/content/groups/tutti-group/fr/ifremer/adagio/… (602 B at 5.5 KB/sec)
mojoStarted org.apache.maven.plugins:maven-clean-plugin:2.5(default-clean)
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ tutti-persistence ---
[INFO] Deleting <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target>
mojoSucceeded org.apache.maven.plugins:maven-clean-plugin:2.5(default-clean)
mojoStarted org.apache.maven.plugins:maven-enforcer-plugin:1.2(check-project-files)
[INFO]
[INFO] --- maven-enforcer-plugin:1.2:enforce (check-project-files) @ tutti-persistence ---
mojoSucceeded org.apache.maven.plugins:maven-enforcer-plugin:1.2(check-project-files)
mojoStarted org.nuiton.eugene:eugene-maven-plugin:2.6.1(default)
[INFO]
[INFO] --- eugene-maven-plugin:2.6.1:generate (default) @ tutti-persistence ---
[INFO] Process phase [zargo] for one entry.
[INFO] Expanding 1 xmi file(s) from <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>
[INFO] Will generate <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…>
[INFO] Copy file <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…> to <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…>
[INFO] Generate one file in 75.758ms.
[INFO] Process phase [xmi] for one entry.
[INFO] Processing XSL tranformation on <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…> for 1 file(s).
[INFO] Will generate <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…>
[INFO] Copy file <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…> to <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…>
[INFO] Generate one file in 2.249s.
[INFO] Process phase [model] for one entry.
INFO [pool-1-thread-1] (ObjectModelReader.java:273) loadModelProperties - 19 tag values were succesfull imported from <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…>
[INFO] Apply generator JavaInterfaceTransformer
[INFO] Apply generator SimpleJavaBeanTransformer
INFO [pool-1-thread-1] (ObjectModelTransformerToJava.java:911) isInClassPath - Will not generate [fr.ifremer.tutti.persistence.entities.data.Program], already found in class-path.
[INFO] Apply generator JavaEnumerationTransformer
mojoSucceeded org.nuiton.eugene:eugene-maven-plugin:2.6.1(default)[INFO] No file generated.
[INFO] Add compile source root : <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…>
[INFO] Add resource root :Resource {targetPath: null, filtering: false, FileSet {directory: <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…,> PatternSet [includes: {}, excludes: {**/*.java}]}}
mojoStarted org.nuiton.i18n:i18n-maven-plugin:2.5(scan-sources)
[INFO]
[INFO] --- i18n-maven-plugin:2.5:parserJava (scan-sources) @ tutti-persistence ---
mojoSucceeded org.nuiton.i18n:i18n-maven-plugin:2.5(scan-sources)
forkedProjectStarted fr.ifremer.tutti:tutti-persistence:1.0-SNAPSHOT
mojoStarted org.nuiton.i18n:i18n-maven-plugin:2.5(get)
[INFO]
[INFO] --- i18n-maven-plugin:2.5:get (get) @ tutti-persistence ---
[INFO] Copying tutti-persistence.properties to <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/ge…>
mojoSucceeded org.nuiton.i18n:i18n-maven-plugin:2.5(get)
forkedProjectSucceeded fr.ifremer.tutti:tutti-persistence:1.0-SNAPSHOT
mojoStarted org.nuiton.i18n:i18n-maven-plugin:2.5(scan-sources)
[INFO]
[INFO] --- i18n-maven-plugin:2.5:gen (scan-sources) @ tutti-persistence ---
[WARNING] bundle fr_FR contains 3/21 empty entries! (use -Di18n.showEmpty to see these entries)
mojoSucceeded org.nuiton.i18n:i18n-maven-plugin:2.5(scan-sources)
mojoStarted org.apache.maven.plugins:maven-resources-plugin:2.6(default-resources)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tutti-persistence ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 11 resources
[INFO] Copying 0 resource
mojoSucceeded org.apache.maven.plugins:maven-resources-plugin:2.6(default-resources)
mojoStarted org.apache.maven.plugins:maven-compiler-plugin:2.5.1(default-compile)
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ tutti-persistence ---
[INFO] Compiling 82 source files to <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/target/cl…>
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] bootstrap class path not set in conjunction with -source 1.6
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[32,44] error: cannot find symbol
[ERROR] symbol: class CatchBatchExtendDao
location: package fr.ifremer.adagio.core.dao.data.batch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[36,54] error: package fr.ifremer.adagio.core.dao.data.batch.validator does not exist
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[37,54] error: package fr.ifremer.adagio.core.dao.data.batch.validator does not exist
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[38,54] error: package fr.ifremer.adagio.core.dao.data.batch.validator does not exist
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[58,72] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidator
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[75,11] error: cannot find symbol
[ERROR] symbol: class CatchBatchExtendDao
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[99,13] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[536,56] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[212,24] error: cannot find symbol
[ERROR] symbol: method getInheritedSortingMeasurements()
location: variable sortingBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[214,20] error: cannot find symbol
[ERROR] symbol: method getInheritedSortingMeasurements()
location: variable sortingBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[92,1] error: method does not override or implement a method from a supertype
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[100,7] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[98,1] error: method does not override or implement a method from a supertype
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[114,11] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationException
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[120,35] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type CatchBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[125,53] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable vracBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[126,50] error: cannot find symbol
[ERROR] symbol: method getWeightBeforeSampling()
location: variable vracBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[132,56] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable speciesBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[133,50] error: cannot find symbol
[ERROR] symbol: method getWeightBeforeSampling()
location: variable speciesBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[139,48] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable inertBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[144,72] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable livingNotItemizedBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[153,50] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable horsVracBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[159,52] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable speciesBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[167,50] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable unsortedBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[270,12] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[270,42] error: cannot find symbol
[ERROR] symbol: method getWeightBeforeSampling()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[271,40] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[274,26] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[275,40] error: cannot find symbol
[ERROR] symbol: method getWeightBeforeSampling()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[297,35] error: cannot find symbol
[ERROR] symbol: method getInheritedReferenceTaxonId()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[432,25] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[567,6] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[567,44] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[570,7] error: cannot find symbol
[ERROR] symbol: variable CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[576,7] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[576,45] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[580,9] error: cannot find symbol
[ERROR] symbol: variable CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[588,4] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[588,42] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[592,6] error: cannot find symbol
[ERROR] symbol: variable CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[597,4] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[597,42] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/src/main/…>:[600,6] error: cannot find symbol
[INFO] 43 errors
[INFO] -------------------------------------------------------------
mojoFailed org.apache.maven.plugins:maven-compiler-plugin:2.5.1(default-compile)
projectFailed fr.ifremer.tutti:tutti-persistence:1.0-SNAPSHOT
sessionEnded
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Tutti ............................................. SUCCESS [6.165s]
[INFO] Tutti :: Persistence .............................. FAILURE [13.074s]
[INFO] Tutti :: Service .................................. SKIPPED
[INFO] Tutti :: UI ....................................... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 20.741s
[INFO] Finished at: Thu Feb 14 16:37:41 CET 2013
[INFO] Final Memory: 28M/116M
[INFO] ------------------------------------------------------------------------
Projects to build: [MavenProject: fr.ifremer:tutti:1.0-SNAPSHOT @ <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/pom.xml,> MavenProject: fr.ifremer.tutti:tutti-persistence:1.0-SNAPSHOT @ <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/pom.xml,> MavenProject: fr.ifremer.tutti:tutti-service:1.0-SNAPSHOT @ <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-service/pom.xml,> MavenProject: fr.ifremer.tutti:tutti-ui-swing:1.0-SNAPSHOT @ <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-ui-swing/pom.xml]>
[JENKINS] Archiving <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-service/pom.xml> to /var/local/jenkins/data/jobs/tutti/modules/fr.ifremer.tutti$tutti-service/builds/2013-02-14_16-37-16/archive/fr.ifremer.tutti/tutti-service/1.0-SNAPSHOT/tutti-service-1.0-SNAPSHOT.pom
[JENKINS] Archiving <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-ui-swing/pom.xml> to /var/local/jenkins/data/jobs/tutti/modules/fr.ifremer.tutti$tutti-ui-swing/builds/2013-02-14_16-37-16/archive/fr.ifremer.tutti/tutti-ui-swing/1.0-SNAPSHOT/tutti-ui-swing-1.0-SNAPSHOT.pom
[JENKINS] Archiving <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/pom.xml> to /var/local/jenkins/data/jobs/tutti/modules/fr.ifremer$tutti/builds/2013-02-14_16-37-16/archive/fr.ifremer/tutti/1.0-SNAPSHOT/tutti-1.0-SNAPSHOT.pom
[JENKINS] Archiving <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/target/tutti-1.0-SNAPSHOT-s…> to /var/local/jenkins/data/jobs/tutti/modules/fr.ifremer$tutti/builds/2013-02-14_16-37-16/archive/fr.ifremer/tutti/1.0-SNAPSHOT/tutti-1.0-SNAPSHOT-site_fr.xml
[JENKINS] Archiving <http://ci.nuiton.org/jenkins/job/tutti/ws/trunk/tutti-persistence/pom.xml> to /var/local/jenkins/data/jobs/tutti/modules/fr.ifremer.tutti$tutti-persistence/builds/2013-02-14_16-37-16/archive/fr.ifremer.tutti/tutti-persistence/1.0-SNAPSHOT/tutti-persistence-1.0-SNAPSHOT.pom
Waiting for Jenkins to finish collecting data
mavenExecutionResult exceptions not empty
message : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile) on project tutti-persistence: Compilation failure
cause : Compilation failure
Stack trace :
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile) on project tutti-persistence: Compilation failure
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.jvnet.hudson.maven3.launcher.Maven3Launcher.main(Maven3Launcher.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchStandard(Launcher.java:329)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:239)
at org.jvnet.hudson.maven3.agent.Maven3Main.launch(Maven3Main.java:158)
at hudson.maven.Maven3Builder.call(Maven3Builder.java:98)
at hudson.maven.Maven3Builder.call(Maven3Builder.java:64)
at hudson.remoting.UserRequest.perform(UserRequest.java:118)
at hudson.remoting.UserRequest.perform(UserRequest.java:48)
at hudson.remoting.Request$2.run(Request.java:326)
at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:729)
at org.apache.maven.plugin.CompilerMojo.execute(CompilerMojo.java:128)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
... 27 more
Sending e-mails to: tutti-commits(a)list.forge.codelutin.com blavenier(a)codelutin.com
channel stopped
1
1
15 Feb '13
See <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/3…>
Changes:
[blavenier] Fix :
- saveBatchFrequencies now delete extra batch
- store weights for 'inert' and 'livingNotSorted'
Add :
- ReferentialPersistenceService.getSampleCategoryIds()
Improve :
- Merge CatchBatchPersistenceService and SpeciesBatchPersistenceService into BatchPersistenceService
- batch management now use adagio implementation CatchBatchExtendDao
------------------------------------------
projectStarted fr.ifremer.tutti:tutti-persistence:1.0-SNAPSHOT
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Tutti :: Persistence 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: http://nexus.nuiton.org/nexus/content/groups/public/fr/ifremer/adagio/adagi…
Downloading: http://nexus.nuiton.org/nexus/content/groups/tutti-group/fr/ifremer/adagio/…
Downloaded: http://nexus.nuiton.org/nexus/content/groups/tutti-group/fr/ifremer/adagio/… (2 KB at 4.5 KB/sec)
Downloading: http://nexus.nuiton.org/nexus/content/groups/tutti-group/fr/ifremer/adagio/…
Downloading: http://nexus.nuiton.org/nexus/content/groups/public/fr/ifremer/adagio/adagi…
Downloaded: http://nexus.nuiton.org/nexus/content/groups/tutti-group/fr/ifremer/adagio/… (602 B at 5.5 KB/sec)
mojoStarted org.apache.maven.plugins:maven-clean-plugin:2.5(default-clean)
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ tutti-persistence ---
[INFO] Deleting <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
mojoSucceeded org.apache.maven.plugins:maven-clean-plugin:2.5(default-clean)
mojoStarted org.apache.maven.plugins:maven-enforcer-plugin:1.2(check-project-files)
[INFO]
[INFO] --- maven-enforcer-plugin:1.2:enforce (check-project-files) @ tutti-persistence ---
mojoSucceeded org.apache.maven.plugins:maven-enforcer-plugin:1.2(check-project-files)
mojoStarted org.nuiton.eugene:eugene-maven-plugin:2.6.1(default)
[INFO]
[INFO] --- eugene-maven-plugin:2.6.1:generate (default) @ tutti-persistence ---
[INFO] Process phase [zargo] for one entry.
[INFO] Expanding 1 xmi file(s) from <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
[INFO] Will generate <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
[INFO] Copy file <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…> to <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
[INFO] Generate one file in 75.758ms.
[INFO] Process phase [xmi] for one entry.
[INFO] Processing XSL tranformation on <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…> for 1 file(s).
[INFO] Will generate <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
[INFO] Copy file <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…> to <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
[INFO] Generate one file in 2.249s.
[INFO] Process phase [model] for one entry.
INFO [pool-1-thread-1] (ObjectModelReader.java:273) loadModelProperties - 19 tag values were succesfull imported from <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
[INFO] Apply generator JavaInterfaceTransformer
[INFO] Apply generator SimpleJavaBeanTransformer
INFO [pool-1-thread-1] (ObjectModelTransformerToJava.java:911) isInClassPath - Will not generate [fr.ifremer.tutti.persistence.entities.data.Program], already found in class-path.
[INFO] Apply generator JavaEnumerationTransformer
mojoSucceeded org.nuiton.eugene:eugene-maven-plugin:2.6.1(default)[INFO] No file generated.
[INFO] Add compile source root : <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
[INFO] Add resource root :Resource {targetPath: null, filtering: false, FileSet {directory: <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…,> PatternSet [includes: {}, excludes: {**/*.java}]}}
mojoStarted org.nuiton.i18n:i18n-maven-plugin:2.5(scan-sources)
[INFO]
[INFO] --- i18n-maven-plugin:2.5:parserJava (scan-sources) @ tutti-persistence ---
mojoSucceeded org.nuiton.i18n:i18n-maven-plugin:2.5(scan-sources)
forkedProjectStarted fr.ifremer.tutti:tutti-persistence:1.0-SNAPSHOT
mojoStarted org.nuiton.i18n:i18n-maven-plugin:2.5(get)
[INFO]
[INFO] --- i18n-maven-plugin:2.5:get (get) @ tutti-persistence ---
[INFO] Copying tutti-persistence.properties to <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
mojoSucceeded org.nuiton.i18n:i18n-maven-plugin:2.5(get)
forkedProjectSucceeded fr.ifremer.tutti:tutti-persistence:1.0-SNAPSHOT
mojoStarted org.nuiton.i18n:i18n-maven-plugin:2.5(scan-sources)
[INFO]
[INFO] --- i18n-maven-plugin:2.5:gen (scan-sources) @ tutti-persistence ---
[WARNING] bundle fr_FR contains 3/21 empty entries! (use -Di18n.showEmpty to see these entries)
mojoSucceeded org.nuiton.i18n:i18n-maven-plugin:2.5(scan-sources)
mojoStarted org.apache.maven.plugins:maven-resources-plugin:2.6(default-resources)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tutti-persistence ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 11 resources
[INFO] Copying 0 resource
mojoSucceeded org.apache.maven.plugins:maven-resources-plugin:2.6(default-resources)
mojoStarted org.apache.maven.plugins:maven-compiler-plugin:2.5.1(default-compile)
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ tutti-persistence ---
[INFO] Compiling 82 source files to <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] bootstrap class path not set in conjunction with -source 1.6
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[32,44] error: cannot find symbol
[ERROR] symbol: class CatchBatchExtendDao
location: package fr.ifremer.adagio.core.dao.data.batch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[36,54] error: package fr.ifremer.adagio.core.dao.data.batch.validator does not exist
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[37,54] error: package fr.ifremer.adagio.core.dao.data.batch.validator does not exist
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[38,54] error: package fr.ifremer.adagio.core.dao.data.batch.validator does not exist
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[58,72] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidator
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[75,11] error: cannot find symbol
[ERROR] symbol: class CatchBatchExtendDao
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[99,13] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[536,56] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[212,24] error: cannot find symbol
[ERROR] symbol: method getInheritedSortingMeasurements()
location: variable sortingBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[214,20] error: cannot find symbol
[ERROR] symbol: method getInheritedSortingMeasurements()
location: variable sortingBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[92,1] error: method does not override or implement a method from a supertype
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[100,7] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[98,1] error: method does not override or implement a method from a supertype
[ERROR] <http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[114,11] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationException
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[120,35] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type CatchBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[125,53] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable vracBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[126,50] error: cannot find symbol
[ERROR] symbol: method getWeightBeforeSampling()
location: variable vracBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[132,56] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable speciesBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[133,50] error: cannot find symbol
[ERROR] symbol: method getWeightBeforeSampling()
location: variable speciesBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[139,48] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable inertBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[144,72] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable livingNotItemizedBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[153,50] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable horsVracBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[159,52] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable speciesBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[167,50] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable unsortedBatch of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[270,12] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[270,42] error: cannot find symbol
[ERROR] symbol: method getWeightBeforeSampling()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[271,40] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[274,26] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[275,40] error: cannot find symbol
[ERROR] symbol: method getWeightBeforeSampling()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[297,35] error: cannot find symbol
[ERROR] symbol: method getInheritedReferenceTaxonId()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[432,25] error: cannot find symbol
[ERROR] symbol: method getWeight()
location: variable source of type SortingBatch
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[567,6] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[567,44] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[570,7] error: cannot find symbol
[ERROR] symbol: variable CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[576,7] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[576,45] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[580,9] error: cannot find symbol
[ERROR] symbol: variable CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[588,4] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[588,42] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[592,6] error: cannot find symbol
[ERROR] symbol: variable CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[597,4] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[597,42] error: cannot find symbol
[ERROR] symbol: class CatchBatchValidationError
location: class BatchPersistenceServiceImpl
<http://ci.nuiton.org/jenkins/job/tutti/fr.ifremer.tutti$tutti-persistence/w…>:[600,6] error: cannot find symbol
[INFO] 43 errors
[INFO] -------------------------------------------------------------
mojoFailed org.apache.maven.plugins:maven-compiler-plugin:2.5.1(default-compile)
projectFailed fr.ifremer.tutti:tutti-persistence:1.0-SNAPSHOT
1
1
r418 - in trunk/tutti-ui-swing/src/main: java/fr/ifremer/tutti/ui/swing java/fr/ifremer/tutti/ui/swing/content/operation java/fr/ifremer/tutti/ui/swing/content/operation/catches java/fr/ifremer/tutti/ui/swing/util/editor resources/i18n
by tchemit@users.forge.codelutin.com 14 Feb '13
by tchemit@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: tchemit
Date: 2013-02-15 00:59:54 +0100 (Fri, 15 Feb 2013)
New Revision: 418
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/418
Log:
- fix new fishing operation (when need to save previous fishing operation)
- begin to integrate synchro db
- improve update ui
- add missing svn properties and license headers
- continue action api
- fix exceptionHandler when action is running
Modified:
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/AbstractTuttiAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/MainUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiApplicationUpdaterCallBack.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiExceptionHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUIContext.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/UpdateApplicationAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/UpdateReferentialAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/NewFishingOperationAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java
trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/AbstractTuttiAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/AbstractTuttiAction.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/AbstractTuttiAction.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -29,20 +29,16 @@
import fr.ifremer.tutti.service.DecoratorService;
import fr.ifremer.tutti.service.TuttiService;
import fr.ifremer.tutti.ui.swing.config.TuttiApplicationConfig;
+import fr.ifremer.tutti.ui.swing.util.action.TuttiActionUI;
+import fr.ifremer.tutti.ui.swing.util.action.TuttiActionUIModel;
import jaxx.runtime.SwingUtil;
+import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdesktop.beans.AbstractBean;
import org.nuiton.util.decorator.Decorator;
import javax.swing.AbstractAction;
-import javax.swing.JDialog;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.border.EmptyBorder;
-import javax.swing.border.TitledBorder;
-import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.Set;
import java.util.Timer;
@@ -50,8 +46,6 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import static org.nuiton.i18n.I18n._;
-
/**
* TODO
*
@@ -72,6 +66,8 @@
private final H handler;
+ private boolean failed;
+
private final boolean hideBody;
private final static Object lock = new Object();
@@ -84,6 +80,7 @@
String text,
String tip,
boolean hideBody) {
+
this.handler = handler;
this.hideBody = hideBody;
putValue(SMALL_ICON, SwingUtil.createActionIcon(icon));
@@ -101,7 +98,7 @@
return (String) getValue("actionName");
}
- protected String getActionDescription() {
+ public String getActionDescription() {
return (String) getValue("actionDescription");
}
@@ -116,6 +113,14 @@
putValue("actionDescription", null);
}
+ public boolean isFailed() {
+ return failed;
+ }
+
+ public void setFailed(boolean failed) {
+ this.failed = failed;
+ }
+
@Override
public final void actionPerformed(final ActionEvent event) {
@@ -123,6 +128,8 @@
log.info("Task [" + this + "] starting");
}
+ setFailed(false);
+
boolean doAction = prepareAction(event);
if (doAction) {
@@ -132,6 +139,7 @@
synchronized (lock) {
useTimer = actions.isEmpty();
+ mainAction = AbstractTuttiAction.this;
actions.add(AbstractTuttiAction.this);
}
@@ -165,17 +173,19 @@
timer = new ActionTimerTask(this);
- t.schedule(timer, 500);
+ t.schedule(timer, 1000);
}
try {
this.doAction(event);
} catch (Throwable e) {
+ setFailed(true);
+
if (log.isErrorEnabled()) {
log.error("Task [" + this + "] error: " + e.getMessage(), e);
}
- throw new TuttiExceptionHandler.TuttiActionException(e);
+ throw new TuttiExceptionHandler.TuttiActionException(this, e);
} finally {
if (log.isInfoEnabled()) {
log.info("Task [" + this + "] done");
@@ -190,7 +200,21 @@
} finally {
synchronized (lock) {
+
+ TuttiActionUI actionUI = AbstractTuttiAction.this.getContext().getActionUI();
+
+ TuttiActionUIModel actionUIModel = actionUI.getModel();
+
+ if (ObjectUtils.equals(AbstractTuttiAction.this, actionUIModel.getAction())) {
+
+ // same action, then remove it (will close dialog as a side effect)
+ actionUIModel.clear();
+ }
actions.remove(AbstractTuttiAction.this);
+
+ if (AbstractTuttiAction.this.equals(getMainAction())) {
+ mainAction = null;
+ }
}
}
}
@@ -226,21 +250,25 @@
private final static Set<Object> actions = Sets.newHashSet();
+ private static AbstractTuttiAction mainAction;
+
+ public static AbstractTuttiAction getMainAction() {
+ return mainAction;
+ }
+
protected static class ActionTimerTask<A extends AbstractTuttiAction> extends TimerTask {
private final Object lock = new Object();
protected boolean canceled;
- private final String actionDescription;
+ private final A action;
- private JDialog d;
+ protected TuttiActionUI actionUI;
- private final A action;
-
public ActionTimerTask(A action) {
this.action = action;
- this.actionDescription = action.getActionDescription();
+ this.actionUI = action.getContext().getActionUI();
}
@Override
@@ -253,41 +281,18 @@
}
} else {
- MainUI ui = action.getContext().getMainUI();
-
-
if (log.isDebugEnabled()) {
log.debug("Task [" + action + "] is started, show waiting dialog");
}
- JPanel panel = new JPanel(new BorderLayout());
- panel.setBorder(new TitledBorder((String) null));
- JLabel label = new JLabel();
- EmptyBorder border = new EmptyBorder(5, 5, 5, 5);
- label.setBorder(border);
- label.setText(_("tutti.message.action.running", actionDescription));
- panel.add(label, BorderLayout.CENTER);
- JProgressBar progressBar = new JProgressBar();
- progressBar.setBorder(border);
- progressBar.setIndeterminate(true);
- panel.add(progressBar, BorderLayout.SOUTH);
-
-
- d = new JDialog(ui, true);
- d.setUndecorated(true);
-// d.setSize(300, 200);
- d.add(panel);
- d.pack();
- SwingUtil.center(ui, d);
-
if (log.isDebugEnabled()) {
log.debug("Try to open dialog (was canceled ? " + canceled + ")");
}
- if (!canceled) {
+ if (!canceled || !action.isFailed()) {
- updateBusyState(ui, true);
+ updateBusyState(true);
- d.setVisible(true);
+ actionUI.getModel().setAction(action);
}
}
}
@@ -302,17 +307,20 @@
}
boolean cancel = super.cancel();
- updateBusyState(action.getContext().getMainUI(), false);
+ updateBusyState(false);
- if (d != null) {
- d.setVisible(false);
+ if (ObjectUtils.equals(action, actionUI.getModel().getAction())) {
+
+ // same action, then remove it (will close dialog as a side effect)
+ actionUI.getModel().clear();
}
return cancel;
}
}
- protected void updateBusyState(MainUI ui, boolean busy) {
+ protected void updateBusyState(boolean busy) {
+ MainUI ui = action.getContext().getMainUI();
if (busy) {
// ui bloquee
if (action.isHideBody()) {
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/MainUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/MainUIHandler.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/MainUIHandler.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -36,6 +36,7 @@
import fr.ifremer.tutti.ui.swing.content.program.EditProgramUI;
import fr.ifremer.tutti.ui.swing.content.protocol.EditProtocolUI;
import fr.ifremer.tutti.ui.swing.content.referential.ManageTemporaryReferentialUI;
+import fr.ifremer.tutti.ui.swing.util.action.TuttiActionUI;
import jaxx.runtime.swing.AboutPanel;
import jaxx.runtime.validator.swing.SwingValidator;
import org.apache.commons.logging.Log;
@@ -74,6 +75,7 @@
super(context, ui);
this.persistenceService = context.getService(PersistenceService.class);
context.setMainUI(ui);
+ context.setActionUI(new TuttiActionUI(ui, context));
}
protected MainUIHandler(TuttiUIContext context) {
@@ -393,6 +395,11 @@
}
} catch (Exception e) {
+ AbstractTuttiAction mainAction = AbstractTuttiAction.getMainAction();
+ if (mainAction != null) {
+ mainAction.setFailed(true);
+ }
+
TuttiUIContext.getErrorHelper().showErrorDialog(
"Could not change to screen " + screen, e);
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiApplicationUpdaterCallBack.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiApplicationUpdaterCallBack.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiApplicationUpdaterCallBack.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -25,7 +25,12 @@
*/
import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+import fr.ifremer.tutti.persistence.ProgressionModel;
+import fr.ifremer.tutti.persistence.service.synchro.ReferentialSynchronizeResult;
+import fr.ifremer.tutti.service.referential.TuttiReferentialSynchronizeService;
+import fr.ifremer.tutti.ui.swing.util.action.TuttiActionUI;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -34,6 +39,7 @@
import java.io.File;
import java.io.IOException;
+import java.util.List;
import java.util.Map;
/**
@@ -57,14 +63,17 @@
protected final TuttiUIContext context;
- protected UpdateType[] types;
+ protected List<UpdateType> types;
- public TuttiApplicationUpdaterCallBack(TuttiUIContext context) {
+ protected ProgressionModel progressionModel;
+
+ public TuttiApplicationUpdaterCallBack(TuttiUIContext context, ProgressionModel progressionModel) {
this.context = context;
+ this.progressionModel = progressionModel;
}
public void setTypes(UpdateType... types) {
- this.types = types;
+ this.types = Lists.newArrayList(types);
}
@Override
@@ -84,10 +93,43 @@
}
}
}
+ if (types.contains(UpdateType.DB)) {
+
+ ApplicationUpdater.ApplicationInfo info = getInfo(UpdateType.DB, result);
+ if (info == null) {
+ String message = "Aucune mise à jour de base détectée.";
+ context.showInformationMessage(message);
+ }
+ }
return result;
}
@Override
+ public void startUpdate(ApplicationUpdater.ApplicationInfo info) {
+ if (UpdateType.DB.name().toLowerCase().equals(info.name)) {
+
+ if (Version.VZERO.toString().equals(info.oldVersion)) {
+
+ progressionModel.setMessage("Téléchargement et installation de la base (version " + info.newVersion + ")");
+ } else {
+ progressionModel.setMessage("Téléchargement et mise à jour de la base (version " + info.newVersion + ")");
+ }
+
+ }
+ if (UpdateType.JRE.name().toLowerCase().equals(info.name)) {
+ progressionModel.setMessage("Téléchargement et installation d'une nouvelle JRE (version " + info.newVersion + ")");
+ }
+
+ if (UpdateType.TUTTI.name().toLowerCase().equals(info.name)) {
+ progressionModel.setMessage("Téléchargement et installation d'une nouvelle version de Tutti (version " + info.newVersion + ")");
+ }
+
+ if (UpdateType.I18N.name().toLowerCase().equals(info.name)) {
+ progressionModel.setMessage("Téléchargement et installation d'une nouveau version I18N (version " + info.newVersion + ")");
+ }
+ }
+
+ @Override
public void updateDone(Map<String, ApplicationUpdater.ApplicationInfo> appToUpdate,
Map<String, Exception> appUpdateError) {
@@ -227,17 +269,20 @@
return appUpdateError.get(type.name().toLowerCase());
}
+ protected File getDbDirectory(ApplicationUpdater.ApplicationInfo info) {
+ File[] sources = info.destDir.listFiles();
+ Preconditions.checkState(
+ sources != null && sources.length == 1,
+ "Downloaded db should contains one directory at " + info.destDir);
+ File result = sources[0];
+ return result;
+ }
+
protected void prepareFirstDatabase(ApplicationUpdater.ApplicationInfo info) {
- //TODO copie base au bon endroit pour utilisation directe
if (log.isInfoEnabled()) {
log.info("First time database was downloaded at version: " + info.newVersion);
}
-
- File[] sources = info.destDir.listFiles();
- Preconditions.checkState(
- sources != null && sources.length == 1,
- "Downloaded db should contains one directory at " + info.destDir);
- File source = sources[0];
+ File source = getDbDirectory(info);
File target = context.getConfig().getServiceConfig().getPersistenceConfig().getDbDirectory();
if (log.isInfoEnabled()) {
log.info("Copy from " + source + " to " + target);
@@ -252,7 +297,6 @@
} catch (IOException e) {
throw new RuntimeException("Could not delete temporary directory " + target, e);
}
-
}
protected void synchronizetDatabase(ApplicationUpdater.ApplicationInfo info) {
@@ -260,5 +304,12 @@
if (log.isInfoEnabled()) {
log.info(String.format("A database update was downloaded (oldVersion: %s, newVersion: %s), will launch a referential synchronize operation ", info.oldVersion, info.newVersion));
}
+ TuttiReferentialSynchronizeService service = context.getService(TuttiReferentialSynchronizeService.class);
+ ReferentialSynchronizeResult result = new ReferentialSynchronizeResult();
+ File dbDirectory = getDbDirectory(info);
+
+ TuttiActionUI actionUI = context.getActionUI();
+ actionUI.getModel().setProgressionModel(result.getProgressionModel());
+ service.prepare(dbDirectory, result);
}
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiExceptionHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiExceptionHandler.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiExceptionHandler.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -48,9 +48,17 @@
private static final long serialVersionUID = 1L;
- public TuttiActionException(Throwable cause) {
+ private final AbstractTuttiAction action;
+
+ public TuttiActionException(AbstractTuttiAction action,
+ Throwable cause) {
super(cause);
+ this.action = action;
}
+
+ public AbstractTuttiAction getAction() {
+ return action;
+ }
}
@Override
@@ -70,16 +78,33 @@
Throwable cause = ex;
+ if (cause instanceof TuttiTechnicalException) {
+ cause = cause.getCause();
+ }
- if (cause instanceof TuttiTechnicalException ||
- cause instanceof TuttiActionException) {
+ boolean backToScreen = false;
+
+ AbstractTuttiAction action = null;
+ if (cause instanceof TuttiActionException) {
+
+ TuttiActionException actionException = (TuttiActionException) cause;
cause = cause.getCause();
+
+ // close action ui
+
+ action = actionException.getAction();
+
+ if (action instanceof AbstractChangeScreenAction) {
+ backToScreen = true;
+ }
+ action.getContext().getActionUI().getModel().setAction(null);
}
-// while (cause != null && !(cause instanceof TuttiTechnicalException)) {
-// cause = cause.getCause();
-// }
TuttiUIContext.getErrorHelper().showErrorDialog(cause.getMessage(), ex);
+
+ if (backToScreen) {
+ action.getContext().setScreen(TuttiScreen.SELECT_CRUISE);
+ }
}
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUIContext.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUIContext.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/TuttiUIContext.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -35,6 +35,7 @@
import fr.ifremer.tutti.service.TuttiServiceContext;
import fr.ifremer.tutti.ui.swing.config.TuttiApplicationConfig;
import fr.ifremer.tutti.ui.swing.util.UIMessageNotifier;
+import fr.ifremer.tutti.ui.swing.util.action.TuttiActionUI;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
@@ -171,6 +172,8 @@
private MainUI mainUI;
+ private TuttiActionUI actionUI;
+
public static TuttiUIContext newContext(TuttiApplicationConfig config) {
Preconditions.checkNotNull(config);
Preconditions.checkState(applicationContext == null,
@@ -192,7 +195,7 @@
this.resourceLoader = new RessourceClassLoader(Thread.currentThread().getContextClassLoader());
this.serviceContext = new TuttiServiceContext(resourceLoader, config.getServiceConfig());
this.swingSession = new SwingSession(getConfig().getUIConfigFile(), false);
- this.errorHelper= new TuttiErrorHelper(this);
+ this.errorHelper = new TuttiErrorHelper(this);
UIMessageNotifier logMessageNotifier = new UIMessageNotifier() {
@Override
@@ -358,6 +361,8 @@
I18n.init(new UserI18nInitializer(
i18nDirectory, new DefaultI18nInitializer("tutti-i18n")),
i18nLocale);
+
+ setActionUI(new TuttiActionUI(null, this));
}
public void open() {
@@ -490,6 +495,16 @@
removePropertyChangeListener(listener);
}
setMainUI(null);
+ if (actionUI != null) {
+
+ // close action ui
+ actionUI.getModel().setProgressionModel(null);
+ actionUI.getModel().setAction(null);
+
+// // hide it
+// actionUI.setVisible(false);
+ }
+ setActionUI(null);
}
protected void saveContextToConfig() {
@@ -525,4 +540,12 @@
public MainUI getMainUI() {
return mainUI;
}
+
+ public void setActionUI(TuttiActionUI actionUI) {
+ this.actionUI = actionUI;
+ }
+
+ public TuttiActionUI getActionUI() {
+ return actionUI;
+ }
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/UpdateApplicationAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/UpdateApplicationAction.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/UpdateApplicationAction.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -24,6 +24,7 @@
* #L%
*/
+import fr.ifremer.tutti.persistence.ProgressionModel;
import fr.ifremer.tutti.ui.swing.config.TuttiApplicationConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -79,8 +80,12 @@
}
ApplicationUpdater up = new ApplicationUpdater();
+ ProgressionModel progressionModel = new ProgressionModel();
+ getContext().getActionUI().getModel().setProgressionModel(progressionModel);
+ progressionModel.setMessage("Recherche de mises à jour de JRE / Tutti / I18N");
+
TuttiApplicationUpdaterCallBack callback =
- new TuttiApplicationUpdaterCallBack(getContext());
+ new TuttiApplicationUpdaterCallBack(getContext(), progressionModel);
callback.setTypes(TuttiApplicationUpdaterCallBack.UpdateType.JRE,
TuttiApplicationUpdaterCallBack.UpdateType.I18N,
@@ -90,6 +95,7 @@
dest,
false,
callback);
+ getContext().getActionUI().getModel().setProgressionModel(null);
}
}
}
\ No newline at end of file
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/UpdateReferentialAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/UpdateReferentialAction.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/UpdateReferentialAction.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -24,6 +24,7 @@
* #L%
*/
+import fr.ifremer.tutti.persistence.ProgressionModel;
import fr.ifremer.tutti.ui.swing.config.TuttiApplicationConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -70,12 +71,17 @@
ApplicationUpdater up = new ApplicationUpdater();
File dest = new File(config.getTuttiBasedir(), "NEW");
- TuttiApplicationUpdaterCallBack callback = new TuttiApplicationUpdaterCallBack(getContext());
+ ProgressionModel progressionModel = new ProgressionModel();
+ getContext().getActionUI().getModel().setProgressionModel(progressionModel);
+ progressionModel.setMessage("Recherche de mises à jour de base");
+ TuttiApplicationUpdaterCallBack callback = new TuttiApplicationUpdaterCallBack(getContext(), progressionModel);
callback.setTypes(TuttiApplicationUpdaterCallBack.UpdateType.DB);
up.update(url,
current,
dest,
false,
callback);
+
+ getContext().getActionUI().getModel().setProgressionModel(null);
}
}
\ No newline at end of file
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationAction.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/EditFishingOperationAction.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -40,6 +40,7 @@
import fr.ifremer.tutti.ui.swing.content.operation.fishing.gearshooting.GearShootingTabUI;
import fr.ifremer.tutti.ui.swing.content.operation.fishing.hydrology.HydrologyTabUI;
import fr.ifremer.tutti.ui.swing.util.TuttiBeanMonitor;
+import jaxx.runtime.SwingUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.util.decorator.Decorator;
@@ -150,6 +151,15 @@
true);
}
+ protected EditFishingOperationAction(FishingOperationsUIHandler handler,
+ String name,
+ String icon,
+ String text,
+ String tip,
+ boolean hideBody) {
+ super(handler, name,icon,text,tip,hideBody);
+ }
+
public void setFishingOperation(FishingOperation fishingOperation) {
this.fishingOperation = fishingOperation;
}
@@ -179,7 +189,6 @@
return saveCatchBatchAction;
}
-
@Override
protected boolean prepareAction(ActionEvent event) {
boolean canContinue = super.prepareAction(event);
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/NewFishingOperationAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/NewFishingOperationAction.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/NewFishingOperationAction.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -28,7 +28,6 @@
import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
import fr.ifremer.tutti.persistence.entities.referential.Gear;
import fr.ifremer.tutti.persistence.entities.referential.Vessel;
-import fr.ifremer.tutti.ui.swing.AbstractTuttiAction;
import fr.ifremer.tutti.ui.swing.util.TuttiUIUtil;
import java.awt.event.ActionEvent;
@@ -42,17 +41,10 @@
* @author tchemit <chemit(a)codelutin.com>
* @since 1.0
*/
-public class NewFishingOperationAction extends AbstractTuttiAction<FishingOperationsUIModel, FishingOperationsUI, FishingOperationsUIHandler> {
+public class NewFishingOperationAction extends EditFishingOperationAction {
private static final long serialVersionUID = 1L;
- /**
- * Delegate action to edit new FishingOperation.
- *
- * @since 1.0
- */
- protected EditFishingOperationAction editFishingOperationAction;
-
public NewFishingOperationAction(FishingOperationsUIHandler handler) {
super(handler,
"newFishingOperation",
@@ -101,16 +93,8 @@
newFishingOperation.setGearShootingStartDate(null);
newFishingOperation.setGearShootingEndDate(null);
+ setFishingOperation(newFishingOperation);
- getEditFishingOperationAction().setFishingOperation(newFishingOperation);
- getEditFishingOperationAction().actionPerformed(event);
-
+ super.doAction(event);
}
-
- public EditFishingOperationAction getEditFishingOperationAction() {
- if (editFishingOperationAction == null) {
- editFishingOperationAction = new EditFishingOperationAction(getHandler());
- }
- return editFishingOperationAction;
- }
}
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -1,6 +1,30 @@
package fr.ifremer.tutti.ui.swing.content.operation.catches;
+/*
+ * #%L
+ * Tutti :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
import fr.ifremer.tutti.service.PersistenceService;
import fr.ifremer.tutti.ui.swing.AbstractTuttiAction;
import fr.ifremer.tutti.ui.swing.content.operation.catches.species.SampleCategory;
Property changes on: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/content/operation/catches/ComputeWeightsAction.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java 2013-02-14 23:59:54 UTC (rev 418)
@@ -1,6 +1,30 @@
package fr.ifremer.tutti.ui.swing.util.editor;
+/*
+ * #%L
+ * Tutti :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
import fr.ifremer.tutti.ui.swing.util.TuttiComputedOrNotData;
import java.awt.Component;
import java.awt.event.FocusEvent;
Property changes on: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/editor/TuttiComputedOrNotDataEditor.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties
===================================================================
--- trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-02-14 23:55:47 UTC (rev 417)
+++ trunk/tutti-ui-swing/src/main/resources/i18n/tutti-ui-swing_fr_FR.properties 2013-02-14 23:59:54 UTC (rev 418)
@@ -98,6 +98,7 @@
tutti.action.newProgram.tip=Créer une nouvelle série de campagne
tutti.action.newProtocol=Nouveau
tutti.action.newProtocol.tip=Créer un nouveau protocole
+tutti.action.ok=Fermer
tutti.action.reload.actions=Recharger les actions
tutti.action.reload.application=Recharger l'application
tutti.action.reload.ui=Recharger l'interface graphique
1
0
r417 - trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential
by tchemit@users.forge.codelutin.com 14 Feb '13
by tchemit@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: tchemit
Date: 2013-02-15 00:55:47 +0100 (Fri, 15 Feb 2013)
New Revision: 417
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/417
Log:
add synchro service
Added:
trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialSynchronizeService.java
Added: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialSynchronizeService.java
===================================================================
--- trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialSynchronizeService.java (rev 0)
+++ trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialSynchronizeService.java 2013-02-14 23:55:47 UTC (rev 417)
@@ -0,0 +1,83 @@
+package fr.ifremer.tutti.service.referential;
+
+/*
+ * #%L
+ * Tutti :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import fr.ifremer.tutti.persistence.config.TuttiPersistenceConfig;
+import fr.ifremer.tutti.persistence.entities.TuttiEntities;
+import fr.ifremer.tutti.persistence.service.TuttiPersistenceServiceLocator;
+import fr.ifremer.tutti.persistence.service.synchro.ReferentialSynchronizeResult;
+import fr.ifremer.tutti.persistence.service.synchro.ReferentialSynchronizeService;
+import fr.ifremer.tutti.service.AbstractTuttiService;
+import fr.ifremer.tutti.service.PersistenceService;
+import fr.ifremer.tutti.service.TuttiServiceContext;
+
+import java.io.File;
+import java.util.Properties;
+
+/**
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class TuttiReferentialSynchronizeService extends AbstractTuttiService {
+
+ protected PersistenceService persistenceService;
+
+ protected ReferentialSynchronizeService synchroService;
+
+ @Override
+ public void setServiceContext(TuttiServiceContext context) {
+ super.setServiceContext(context);
+ synchroService = TuttiPersistenceServiceLocator.getReferentialSynchronizeService();
+ persistenceService = getService(PersistenceService.class);
+ }
+
+ public void prepare(File dbDirectory, ReferentialSynchronizeResult result) {
+ Properties remoteConnectionProperties = getRemoteProperties(dbDirectory);
+ synchroService.prepare(remoteConnectionProperties, result);
+ }
+
+ public void synchronize(File dbDirectory,
+ ReferentialSynchronizeResult result) {
+ Properties remoteConnectionProperties = getRemoteProperties(dbDirectory);
+ synchroService.synchronize(remoteConnectionProperties, result);
+ }
+
+ protected Properties getRemoteProperties(File dbDirectory) {
+ Properties remoteConnectionProperties = new Properties();
+ TuttiPersistenceConfig persistenceConfig =
+ context.getConfig().getPersistenceConfig();
+
+ String jdbcUrl = TuttiEntities.getJdbcUrl(dbDirectory,
+ persistenceConfig.getDbName());
+
+ TuttiEntities.fillConnectionProperties(remoteConnectionProperties,
+ jdbcUrl,
+ persistenceConfig.getJdbcUsername(),
+ persistenceConfig.getJdbcPassword());
+ return remoteConnectionProperties;
+ }
+
+
+}
Property changes on: trunk/tutti-service/src/main/java/fr/ifremer/tutti/service/referential/TuttiReferentialSynchronizeService.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
1
0
r416 - in trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util: . action
by tchemit@users.forge.codelutin.com 14 Feb '13
by tchemit@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: tchemit
Date: 2013-02-15 00:55:36 +0100 (Fri, 15 Feb 2013)
New Revision: 416
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/416
Log:
add action package
Added:
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.css
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.jaxx
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIHandler.java
trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIModel.java
Added: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.css
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.css (rev 0)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.css 2013-02-14 23:55:36 UTC (rev 416)
@@ -0,0 +1,61 @@
+/*
+ * #%L
+ * Tutti :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+#globalPanel {
+ border: {new TitledBorder((String) null)};
+}
+
+#globalActionLabel {
+ border: {new EmptyBorder(5, 5, 5, 5)};
+}
+
+#globalProgressBar {
+ indeterminate: true;
+}
+
+#taskPanel {
+ visible: false;
+ border: {new TitledBorder((String) null)};
+}
+
+#taskProgressBar {
+ indeterminate: false;
+}
+
+#taskActionLabel {
+ border: {new EmptyBorder(5, 5, 5, 5)};
+}
+
+#informationPanel {
+ visible: false;
+ border: {new TitledBorder((String) null)};
+}
+
+#informationLabel {
+ border: {new EmptyBorder(5, 5, 5, 5)};
+}
+
+#okAction {
+ actionIcon: information;
+ text: "tutti.action.ok";
+}
Property changes on: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.css
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.jaxx
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.jaxx (rev 0)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.jaxx 2013-02-14 23:55:36 UTC (rev 416)
@@ -0,0 +1,72 @@
+<!--
+ #%L
+ Tutti :: UI
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2012 - 2013 Ifremer
+ %%
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as
+ published by the Free Software Foundation, either version 3 of the
+ License, or (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/gpl-3.0.html>.
+ #L%
+ -->
+<JDialog layout='{new BorderLayout()}' width='300' height='200' modal='true' undecorated='true'
+ implements='fr.ifremer.tutti.ui.swing.TuttiUI<TuttiActionUIModel, TuttiActionUIHandler>'>
+ <import>
+
+ fr.ifremer.tutti.ui.swing.TuttiUI
+ fr.ifremer.tutti.ui.swing.TuttiUIContext
+
+ javax.swing.border.EmptyBorder
+
+ static org.nuiton.i18n.I18n._
+ </import>
+
+ <script><![CDATA[
+
+ public TuttiActionUI(JFrame frame, TuttiUIContext context) {
+ super(frame, true);
+ TuttiActionUIHandler handler = new TuttiActionUIHandler(context, this);
+ setContextValue(handler);
+ handler.beforeInitUI();
+ }
+
+ protected void $afterCompleteSetup() {
+ handler.afterInitUI();
+ }
+ ]]></script>
+
+ <TuttiActionUIHandler id='handler'
+ initializer='getContextValue(TuttiActionUIHandler.class)'/>
+
+ <TuttiActionUIModel id='model'
+ initializer='getContextValue(TuttiActionUIModel.class)'/>
+
+
+ <JPanel id='globalPanel' constraints='BorderLayout.NORTH'
+ layout='{new BorderLayout()}'>
+ <JLabel id='globalActionLabel' constraints='BorderLayout.CENTER'/>
+ <JProgressBar id='globalProgressBar' constraints='BorderLayout.SOUTH'/>
+ </JPanel>
+ <JPanel id='taskPanel' constraints='BorderLayout.CENTER'
+ layout='{new BorderLayout()}'>
+ <JLabel id='taskActionLabel' constraints='BorderLayout.CENTER'/>
+ <JProgressBar id='taskProgressBar' constraints='BorderLayout.SOUTH'/>
+ </JPanel>
+ <!--JPanel id='informationPanel' constraints='BorderLayout.SOUTH'
+ layout='{new BorderLayout()}'>
+ <JLabel id='informationLabel' constraints='BorderLayout.CENTER'/>
+ <JButton id='okAction' constraints='BorderLayout.SOUTH' onActionPerformed='handler.closeAction()'/>
+ </JPanel-->
+</JDialog>
\ No newline at end of file
Property changes on: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUI.jaxx
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIHandler.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIHandler.java (rev 0)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIHandler.java 2013-02-14 23:55:36 UTC (rev 416)
@@ -0,0 +1,185 @@
+package fr.ifremer.tutti.ui.swing.util.action;
+
+/*
+ * #%L
+ * Tutti :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import fr.ifremer.tutti.persistence.ProgressionModel;
+import fr.ifremer.tutti.ui.swing.AbstractTuttiAction;
+import fr.ifremer.tutti.ui.swing.AbstractTuttiUIHandler;
+import fr.ifremer.tutti.ui.swing.TuttiUIContext;
+import jaxx.runtime.SwingUtil;
+import jaxx.runtime.validator.swing.SwingValidator;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.swing.SwingUtilities;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+
+import static org.nuiton.i18n.I18n._;
+
+/**
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class TuttiActionUIHandler extends AbstractTuttiUIHandler<TuttiActionUIModel, TuttiActionUI> {
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(TuttiActionUIHandler.class);
+
+
+ public TuttiActionUIHandler(TuttiUIContext context, TuttiActionUI ui) {
+ super(context, ui);
+ }
+
+ protected PropertyChangeListener progressionListener = new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+
+ String propertyName = evt.getPropertyName();
+ if (ProgressionModel.PROPERTY_MESSAGE.equals(propertyName)) {
+
+ // change message
+ ui.getTaskActionLabel().setText((String) evt.getNewValue());
+ } else if (ProgressionModel.PROPERTY_TOTAL.equals(propertyName)) {
+
+ // change total progressbar max
+ ui.getTaskProgressBar().setMaximum((Integer) evt.getNewValue());
+
+ } else if (ProgressionModel.PROPERTY_MESSAGE.equals(propertyName)) {
+
+ // change value of progress bar
+ ui.getTaskProgressBar().setValue((Integer) evt.getNewValue());
+ }
+ }
+ };
+
+ //------------------------------------------------------------------------//
+ //-- AbstractTuttiUIHandler methods --//
+ //------------------------------------------------------------------------//
+
+ protected void hideAction() {
+ getModel().setProgressionModel(null);
+ ui.setVisible(false);
+ }
+
+ @Override
+ public void beforeInitUI() {
+ TuttiActionUIModel model = new TuttiActionUIModel();
+ ui.setContextValue(model);
+
+ model.addPropertyChangeListener(TuttiActionUIModel.PROPERTY_ACTION, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+
+ // udpate global label
+ AbstractTuttiAction action = (AbstractTuttiAction) evt.getNewValue();
+
+ if (log.isInfoEnabled()) {
+ log.info("Action to use: " + action);
+ }
+ if (action == null || action.isFailed()) {
+
+ // stoping action
+
+ if (SwingUtilities.isEventDispatchThread()) {
+
+ hideAction();
+ } else {
+ SwingUtilities.invokeLater(new Runnable() {
+ @Override
+ public void run() {
+ hideAction();
+ }
+ });
+ }
+ } else {
+
+ // starting action
+ if (ui.getOwner() != null) {
+
+ SwingUtil.center(ui.getOwner(), ui);
+ }
+ // new action
+ ui.getGlobalActionLabel().setText(_("tutti.message.action.running", action.getActionDescription()));
+ ui.pack();
+ ui.setVisible(true);
+ }
+ }
+ });
+
+ model.addPropertyChangeListener(TuttiActionUIModel.PROPERTY_PROGRESSION_MODEL, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+
+ // change progression model
+
+ ProgressionModel oldValue = (ProgressionModel) evt.getOldValue();
+ ProgressionModel newValue = (ProgressionModel) evt.getNewValue();
+
+ if (log.isInfoEnabled()) {
+ log.info("progression model: " + newValue);
+ }
+ if (oldValue != null) {
+ oldValue.removePropertyChangeListener(progressionListener);
+ }
+
+ if (newValue == null) {
+
+ // remove progression model
+// ui.getGlobalProgressBar().setVisible(true);
+ ui.getTaskPanel().setVisible(false);
+ } else {
+
+ // use progression model
+// ui.getGlobalProgressBar().setVisible(false);
+ ui.getTaskPanel().setVisible(true);
+
+ newValue.addPropertyChangeListener(progressionListener);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void afterInitUI() {
+
+ initUI(ui);
+ }
+
+ @Override
+ public void onCloseUI() {
+
+ }
+
+ @Override
+ public SwingValidator<TuttiActionUIModel> getValidator() {
+ return null;
+ }
+
+ public void closeAction() {
+ getModel().clear();
+ }
+}
Property changes on: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIHandler.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIModel.java
===================================================================
--- trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIModel.java (rev 0)
+++ trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIModel.java 2013-02-14 23:55:36 UTC (rev 416)
@@ -0,0 +1,71 @@
+package fr.ifremer.tutti.ui.swing.util.action;
+
+/*
+ * #%L
+ * Tutti :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import fr.ifremer.tutti.persistence.ProgressionModel;
+import fr.ifremer.tutti.ui.swing.AbstractTuttiAction;
+import org.jdesktop.beans.AbstractSerializableBean;
+
+/**
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class TuttiActionUIModel extends AbstractSerializableBean {
+
+ private static final long serialVersionUID = 1L;
+
+ public static final String PROPERTY_ACTION = "action";
+
+ public static final String PROPERTY_PROGRESSION_MODEL = "progressionModel";
+
+ protected AbstractTuttiAction action;
+
+ protected ProgressionModel progressionModel;
+
+ public ProgressionModel getProgressionModel() {
+ return progressionModel;
+ }
+
+ public void setProgressionModel(ProgressionModel progressionModel) {
+ Object oldValue = getProgressionModel();
+ this.progressionModel = progressionModel;
+ firePropertyChange(PROPERTY_PROGRESSION_MODEL, oldValue, progressionModel);
+ }
+
+ public AbstractTuttiAction getAction() {
+ return action;
+ }
+
+ public void setAction(AbstractTuttiAction action) {
+ Object oldValue = getAction();
+ this.action = action;
+ firePropertyChange(PROPERTY_ACTION, oldValue, action);
+ }
+
+ public void clear() {
+ setProgressionModel(null);
+ setAction(null);
+ }
+}
Property changes on: trunk/tutti-ui-swing/src/main/java/fr/ifremer/tutti/ui/swing/util/action/TuttiActionUIModel.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
1
0
Author: tchemit
Date: 2013-02-15 00:55:08 +0100 (Fri, 15 Feb 2013)
New Revision: 415
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/415
Log:
begin doc + update last nuiton-utils snapshot
Added:
trunk/src/site/rst/protocol.rst
trunk/src/site/rst/temporaryReferential.rst
trunk/src/site/rst/update.rst
Modified:
trunk/pom.xml
trunk/src/site/site_fr.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-02-14 23:53:34 UTC (rev 414)
+++ trunk/pom.xml 2013-02-14 23:55:08 UTC (rev 415)
@@ -124,7 +124,7 @@
<!-- libraries version -->
- <nuitonUtilsVersion>2.6.7</nuitonUtilsVersion>
+ <nuitonUtilsVersion>2.6.8-SNAPSHOT</nuitonUtilsVersion>
<nuitonI18nVersion>2.5</nuitonI18nVersion>
<eugenePluginVersion>2.6.1</eugenePluginVersion>
@@ -138,7 +138,7 @@
<slf4jVersion>1.7.2</slf4jVersion>
- <adagioVersion>3.3.1-SNAPSHOT</adagioVersion>
+ <adagioVersion>3.3.2-SNAPSHOT</adagioVersion>
<msaccessImporterVersion>1.4.1</msaccessImporterVersion>
Added: trunk/src/site/rst/protocol.rst
===================================================================
--- trunk/src/site/rst/protocol.rst (rev 0)
+++ trunk/src/site/rst/protocol.rst 2013-02-14 23:55:08 UTC (rev 415)
@@ -0,0 +1,30 @@
+.. -
+.. * #%L
+.. * Tutti
+.. * $Id$
+.. * $HeadURL$
+.. * %%
+.. * Copyright (C) 2012 - 2013 Ifremer
+.. * %%
+.. * This program is free software: you can redistribute it and/or modify
+.. * it under the terms of the GNU General Public License as
+.. * published by the Free Software Foundation, either version 3 of the
+.. * License, or (at your option) any later version.
+.. *
+.. * This program is distributed in the hope that it will be useful,
+.. * but WITHOUT ANY WARRANTY; without even the implied warranty of
+.. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+.. * GNU General Public License for more details.
+.. *
+.. * You should have received a copy of the GNU General Public
+.. * License along with this program. If not, see
+.. * <http://www.gnu.org/licenses/gpl-3.0.html>.
+.. * #L%
+.. -
+
+
+====================
+Gestion du protocole
+====================
+
+TODO
\ No newline at end of file
Property changes on: trunk/src/site/rst/protocol.rst
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/src/site/rst/temporaryReferential.rst
===================================================================
--- trunk/src/site/rst/temporaryReferential.rst (rev 0)
+++ trunk/src/site/rst/temporaryReferential.rst 2013-02-14 23:55:08 UTC (rev 415)
@@ -0,0 +1,30 @@
+.. -
+.. * #%L
+.. * Tutti
+.. * $Id$
+.. * $HeadURL$
+.. * %%
+.. * Copyright (C) 2012 - 2013 Ifremer
+.. * %%
+.. * This program is free software: you can redistribute it and/or modify
+.. * it under the terms of the GNU General Public License as
+.. * published by the Free Software Foundation, either version 3 of the
+.. * License, or (at your option) any later version.
+.. *
+.. * This program is distributed in the hope that it will be useful,
+.. * but WITHOUT ANY WARRANTY; without even the implied warranty of
+.. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+.. * GNU General Public License for more details.
+.. *
+.. * You should have received a copy of the GNU General Public
+.. * License along with this program. If not, see
+.. * <http://www.gnu.org/licenses/gpl-3.0.html>.
+.. * #L%
+.. -
+
+
+====================================
+Gestion des référentiels temporaires
+====================================
+
+TODO
\ No newline at end of file
Property changes on: trunk/src/site/rst/temporaryReferential.rst
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/src/site/rst/update.rst
===================================================================
--- trunk/src/site/rst/update.rst (rev 0)
+++ trunk/src/site/rst/update.rst 2013-02-14 23:55:08 UTC (rev 415)
@@ -0,0 +1,119 @@
+.. -
+.. * #%L
+.. * Tutti
+.. * $Id$
+.. * $HeadURL$
+.. * %%
+.. * Copyright (C) 2012 - 2013 Ifremer
+.. * %%
+.. * This program is free software: you can redistribute it and/or modify
+.. * it under the terms of the GNU General Public License as
+.. * published by the Free Software Foundation, either version 3 of the
+.. * License, or (at your option) any later version.
+.. *
+.. * This program is distributed in the hope that it will be useful,
+.. * but WITHOUT ANY WARRANTY; without even the implied warranty of
+.. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+.. * GNU General Public License for more details.
+.. *
+.. * You should have received a copy of the GNU General Public
+.. * License along with this program. If not, see
+.. * <http://www.gnu.org/licenses/gpl-3.0.html>.
+.. * #L%
+.. -
+
+=======================
+Mise à jour du logiciel
+=======================
+
+Présentation
+------------
+
+**Tutti** utilise un mécanisme simple pour effectuer les mises à jour de ses
+différents composants, à savoir:
+
+1. Mise à jour de la JRE
+2. Mise à jour du programme Tutti
+3. Mise à jour des fichiers de traductions
+4. Mise à jour de la base de données.
+
+Principe des mises à jour
+-------------------------
+
+Chaque composant est contenu dans un répertoire et possède un fichier
+obligatoirement nommé **version.appup** qui contient la version du composant.
+
+Un fichier de propriétés disponible sur le réseau à l'adresse suivante:
+http://appup.forge.codelutin.com/tutti/update-tutti.properties
+
+contient la description des dernières version disponibles.
+
+::
+
+ ################################################################################
+ ### JRE Updates ################################################################
+ ################################################################################
+
+ jre.version=1.7.10
+ linux.amd64.jre.url=zip:http://nexus.nuiton.org/nexus/content/repositories/…
+ linux.i386.jre.url=zip:http://nexus.nuiton.org/nexus/content/repositories/j…
+ windows.amd64.jre.url=zip:http://nexus.nuiton.org/nexus/content/repositorie…
+ windows.i386.jre.url=zip:http://nexus.nuiton.org/nexus/content/repositories…
+
+ ################################################################################
+ ### Tutti Updates ##############################################################
+ ################################################################################
+
+ tutti.version=1.0-SNAPSHOT
+ tutti.url=zip:http://nexus.nuiton.org/nexus/content/repositories/other-rele…
+
+ ################################################################################
+ ### I18n Updates ###############################################################
+ ################################################################################
+
+ i18n.version=1.0-SNAPSHOT
+ i18n.url=zip:http://nexus.nuiton.org/nexus/content/repositories/other-relea…
+
+ ################################################################################
+ ### DB Updates #################################################################
+ ################################################################################
+
+ db.version=2013.02.02
+ db.url=zip:http://appup.forge.codelutin.com/tutti/auth/tutti-db-2013.02.02.…
+ db.auth=true
+
+Au démarrage de l'application le fichier est lu et si un des composants est
+plus récent dans la description du fichier de mises à jour, il est téléchargé
+puis l'application l'intègre.
+
+Chaque composant téléchargeable doit être un fichier zip (mais d'autre formats
+d'archivage sont possibles) et contenir un seul répertoire (il n'est pas
+possible d'avoir le composant directement à la racine de l'archive).
+
+Mettre en place une nouvelle mise à jour
+----------------------------------------
+
+Pour pouvoir définir une nouvelle mise à jour, il faut donc modifier le fichier
+de mises à jour :
+
+1. changer la version du composant
+2. changer l'url de téléchargement du composant.
+
+Mise à jour sécurisées
+----------------------
+
+La mise à jour de la base est sécurisée, à savoir que l'url d'accès au zip de
+la base requière un mot de passe.
+
+Le fichier de mise à jour quand à lui sera toujours disponible publiquement.
+
+Pré-requis à la création d'une nouvelle version de Tutti
+--------------------------------------------------------
+
+pour pouvoir créer une nouvelle version de Tutti, il nous faut connaitre la
+dernière mise à jour de la base.
+
+Ainsi nous pourrons monter les version du fichier de mise à jour automatiquement.
+
+Les autres composants (jre, tutti et i18n) sont automatiquement gérés lors de
+la création de la nouvelle version.
\ No newline at end of file
Property changes on: trunk/src/site/rst/update.rst
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/src/site/site_fr.xml
===================================================================
--- trunk/src/site/site_fr.xml 2013-02-14 23:53:34 UTC (rev 414)
+++ trunk/src/site/site_fr.xml 2013-02-14 23:55:08 UTC (rev 415)
@@ -96,7 +96,8 @@
<menu name="Tutti">
<item name="Accueil" href="index.html"/>
- <item name="Configuration" href="./application-config-report.html"/>
+ <item name="Gestion du protocole" href="./protocol.html"/>
+ <item name="Référentiels temporaires" href="./temporaryReferential.html"/>
<item name="Téléchargement"
href="http://forge.codelutin.com/projects/tutti/files"/>
<item name="Roadmap"
@@ -105,7 +106,9 @@
</menu>
<menu name="Documentation Technique">
+ <item name="Configuration" href="./application-config-report.html"/>
<item name="Référentiel" href="referential.html"/>
+ <item name="Mise à jour des versions" href="./update.html"/>
</menu>
<menu ref="reports"/>
1
0
r414 - in trunk/tutti-persistence: . src/main/java/fr/ifremer/tutti/persistence src/main/java/fr/ifremer/tutti/persistence/entities src/main/java/fr/ifremer/tutti/persistence/service src/main/java/fr/ifremer/tutti/persistence/service/synchro src/main/resources src/test/java/fr/ifremer/tutti/persistence src/test/java/fr/ifremer/tutti/persistence/service src/test/java/fr/ifremer/tutti/persistence/service/synchro
by tchemit@users.forge.codelutin.com 14 Feb '13
by tchemit@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: tchemit
Date: 2013-02-15 00:53:34 +0100 (Fri, 15 Feb 2013)
New Revision: 414
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/414
Log:
improve synchro (add progressionModel in result) + add missingsvnproperties,...
Added:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java
Modified:
trunk/tutti-persistence/pom.xml
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java
trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java
Modified: trunk/tutti-persistence/pom.xml
===================================================================
--- trunk/tutti-persistence/pom.xml 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/pom.xml 2013-02-14 23:53:34 UTC (rev 414)
@@ -88,6 +88,11 @@
<artifactId>commons-dbcp</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.swinglabs.swingx</groupId>
+ <artifactId>swingx-common</artifactId>
+ </dependency>
+
<!-- Yaml -->
<dependency>
Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -0,0 +1,101 @@
+package fr.ifremer.tutti.persistence;
+
+/*
+ * #%L
+ * Tutti :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import org.jdesktop.beans.AbstractSerializableBean;
+
+/**
+ * Simple model for a progression long task.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class ProgressionModel extends AbstractSerializableBean {
+
+ private static final long serialVersionUID = 1L;
+
+ public static final String PROPERTY_TOTAL = "total";
+
+ public static final String PROPERTY_CURRENT = "current";
+
+ public static final String PROPERTY_RATE = "rate";
+
+ public static final String PROPERTY_MESSAGE = "message";
+
+ protected int total;
+
+ protected int current;
+
+ protected float rate;
+
+ protected String message;
+
+ public long getTotal() {
+ return total;
+ }
+
+ public void setTotal(int total) {
+ Object oldValue = getTotal();
+ this.total = total;
+ firePropertyChange(PROPERTY_TOTAL, oldValue, total);
+ setCurrent(0);
+ }
+
+ public long getCurrent() {
+ return current;
+ }
+
+ public void setCurrent(int current) {
+ Object oldValue = getCurrent();
+ this.current = current;
+ firePropertyChange(PROPERTY_CURRENT, oldValue, current);
+ }
+
+ public void increments(int nb) {
+ setCurrent(current + nb);
+ setRate(getCurrent() / getTotal());
+ }
+
+ public float getRate() {
+ return rate;
+ }
+
+ public void setRate(float rate) {
+ Object oldValue = getRate();
+ this.rate = rate;
+ firePropertyChange(PROPERTY_RATE, oldValue, rate);
+
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ Object oldValue = getMessage();
+ this.message = message;
+ firePropertyChange(PROPERTY_MESSAGE, oldValue, message);
+ }
+}
Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/ProgressionModel.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/entities/TuttiEntities.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -223,6 +223,10 @@
p.put(Environment.PASS, password);
}
+ public static String getJdbcUrl(File directory, String dbName) {
+ return "jdbc:hsqldb:file:" + directory.getAbsolutePath() + "/" + dbName;
+ }
+
protected static class IdPredicate<B extends IdAware> implements Predicate<B> {
private final String id;
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -1,8 +1,33 @@
-package fr.ifremer.tutti.persistence.service;
-
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional(readOnly = true)
-public interface BatchPersistenceService extends CatchBatchPersistenceService, SpeciesBatchPersistenceService{
-
-}
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional(readOnly = true)
+public interface BatchPersistenceService extends CatchBatchPersistenceService, SpeciesBatchPersistenceService {
+
+}
\ No newline at end of file
Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -1,1297 +1,1322 @@
-package fr.ifremer.tutti.persistence.service;
-
-import static org.nuiton.i18n.I18n._;
-
-import java.io.Serializable;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.annotation.Resource;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.FlushMode;
-import org.hibernate.type.IntegerType;
-import org.springframework.cache.annotation.CacheEvict;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.DataRetrievalFailureException;
-import org.springframework.stereotype.Service;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-
-import fr.ifremer.adagio.core.dao.data.batch.Batch;
-import fr.ifremer.adagio.core.dao.data.batch.CatchBatchExtendDao;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationError;
-import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException;
-import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidator;
-import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
-import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
-import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
-import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
-import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
-import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
-import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus;
-import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
-import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
-import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
-import fr.ifremer.tutti.persistence.entities.referential.Species;
-import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
-
-@Service("batchPersistenceService")
-public class BatchPersistenceServiceImpl
- extends AbstractPersistenceService implements BatchPersistenceService, CatchBatchValidator
- {
-
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(BatchPersistenceServiceImpl.class);
-
- @Resource(name = "referentialPersistenceService")
- protected ReferentialPersistenceService referentialService;
-
- @Resource(name = "denormalizedBatchDao")
- protected DenormalizedBatchDao denormalizedBatchDao;
-
- @Resource(name = "sortingBatchDao")
- protected SortingBatchDao sortingBatchDao;
-
- @Resource(name = "catchBatchDao")
- protected CatchBatchExtendDao catchBatchDao;
-
- @Resource(name = "measurementPersistenceHelper")
- protected MeasurementPersistenceHelper measurementHelper;
-
- @Override
- public void init() {
- super.init();
- catchBatchDao.registerCatchBatchValidator(this);
- }
-
- @Override
- public void close() {
- catchBatchDao.unregisterCatchBatchValidator(this);
- super.close();
- }
-
- @Override
- public boolean isEnable(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
- // Apply validation only on catch batch for fishingOperation
- return (catchBatch.getFishingOperation() != null);
- }
-
- @Override
- public List<CatchBatchValidationError> validate(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
- List<CatchBatchValidationError> errors = Lists.newArrayList();
- validate(catchBatch.getChildBatchs(), errors, 1);
- return errors;
- }
-
- @Override
- public CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) {
- Preconditions.checkNotNull(fishingOperationId);
-
- Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
-
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch source;
- try {
- source = catchBatchDao.loadFullTree(catchBatchId, true, true);
- } catch (CatchBatchValidationException e) {
- throw new DataRetrievalFailureException("Invalid batch tree structure, for fishing operation id=" + fishingOperationId, e);
- }
-
- CatchBatch result = new CatchBatch();
- result.setId(source.getId().toString());
- result.setCatchTotalWeight(source.getWeight());
-
- // Vrac
- SortingBatch vracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID);
- result.setCatchTotalSortedCarousselWeight(vracBatch.getWeight());
- result.setCatchTotalSortedTremisWeight(vracBatch.getWeightBeforeSampling());
- {
- // Species
- SortingBatch speciesBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
-
- result.setSpeciesTotalSampleSortedWeight(speciesBatch.getWeight());
- result.setSpeciesTotalSortedWeight(speciesBatch.getWeightBeforeSampling());
-
- {
- // Inert
- SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
- "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
- result.setSpeciesTotalInertWeight(inertBatch.getWeight());
-
- // Alive no itemized
- SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
- "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
- result.setSpeciesTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight());
- }
-
- // TODO : Benthos, Plancton...
- }
-
- // Hors Vrac
- SortingBatch horsVracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID);
- result.setCatchTotalUnsortedWeight(horsVracBatch.getWeight());
- {
- // Species
- SortingBatch speciesBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
-
- result.setSpeciesTotalUnsortedWeight(speciesBatch.getWeight());
-
- // TODO : Benthos, Plancton...
- }
-
- // Non trié
- SortingBatch unsortedBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID);
- result.setCatchTotalRejectedWeight(unsortedBatch.getWeight());
-
- return result;
- }
-
- @Override
-
- public CatchBatch createCatchBatch(CatchBatch bean) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkArgument(bean.getId() == null);
- Preconditions.checkNotNull(bean.getFishingOperation());
- Preconditions.checkNotNull(bean.getFishingOperation().getId());
-
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = fr.ifremer.adagio.core.dao.data.batch.CatchBatch.Factory.newInstance();
- beanToEntity(bean, catchBatch, true);
- catchBatch = catchBatchDao.create(catchBatch);
- bean.setId(String.valueOf(catchBatch.getId()));
-
- // Link to fishing operation
- getCurrentSession().flush();
- Integer fishingOperationId = Integer.valueOf(bean.getFishingOperation().getId());
- int rowUpdated = queryUpdate("updateFishingOperationCatchBatch",
- "fishingOperationId", IntegerType.INSTANCE, fishingOperationId,
- "catchBatchId", IntegerType.INSTANCE, catchBatch.getId());
- if (rowUpdated == 0) {
- throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found.");
- }
-
- return bean;
- }
-
- @Override
- @CacheEvict(value = "batchTree", key="#bean.fishingOperation.id")
- public CatchBatch saveCatchBatch(CatchBatch bean) {
-
- Preconditions.checkNotNull(bean);
- Preconditions.checkNotNull(bean.getId());
-
- getCurrentSession().enableFetchProfile("batch-with-childs");
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(Integer.valueOf(bean.getId()));
- if (catchBatch == null) {
- throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId());
- }
-
- beanToEntity(bean, catchBatch, true);
- catchBatchDao.update(catchBatch);
- getCurrentSession().flush();
-
- return bean;
- }
-
- @Override
- public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) {
-
- // Load batch tree
- Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- List<SpeciesBatch> result = new ArrayList<SpeciesBatch>();
-
- // Vrac / Species
- SortingBatch vracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- for (Iterator<Batch> iterator = vracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch source = (SortingBatch) iterator.next();
-
- // evict some special batches : Life (or Biota) and Inert
- if (source.getReferenceTaxon() != null
- && enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) == false
- && enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId()) == false) {
- SpeciesBatch target = new SpeciesBatch();
-
- entityToBean(source, target);
- result.add(target);
- }
- }
-
- // Hors-Vrac / Species
- SortingBatch horsVracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
- "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- for (Iterator<Batch> iterator = horsVracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch source = (SortingBatch) iterator.next();
-
- SpeciesBatch target = new SpeciesBatch();
-
- entityToBean(source, target);
- result.add(target);
- }
-
- return result;
- }
-
- protected SpeciesBatch entityToBean(SortingBatch source, SpeciesBatch target) {
-
- target.setId(source.getId().toString());
-
- // Individual count
- target.setNumber(source.getIndividualCount());
-
- // Convert database weight (and sampling ratio) into UI weight and sampleCategoryWeight
- if (source.getWeight() != null && source.getWeightBeforeSampling() == null) {
- target.setSampleCategoryWeight(source.getWeight());
- }
- else {
- target.setWeight(source.getWeight());
- target.setSampleCategoryWeight(source.getWeightBeforeSampling());
- }
-
- // Comments
- target.setComment(source.getComments());
-
- // Sample category type (only one is applied)
- SortingMeasurement sm = null;
- if (source.getSortingMeasurements().size() == 1) {
- sm = source.getSortingMeasurements().iterator().next();
- }
- else if (source.getReferenceTaxon() != null && source.getReferenceTaxon().getId() != null){
- sm = measurementHelper.getInheritedSortingMeasurement(source, enumeration.PMFM_ID_SORTED_UNSORTED);
- }
- if (sm != null) {
- SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(sm.getPmfm().getId());
- if (sampleCategory != null) {
- setSampleCategoryQualitative(target, sm.getPmfm().getId(), sm.getNumericalValue(), sm.getAlphanumericalValue(), sm.getQualitativeValue().getId());
- }
- }
-
- // Species
- Integer referenceTaxonId = source.getInheritedReferenceTaxonId();
- if (referenceTaxonId == null && source.getReferenceTaxon() != null) {
- referenceTaxonId = source.getReferenceTaxon().getId();
- }
- if (referenceTaxonId != null) {
- // TODO : add cache on getSpeciesByReferenceTaxonId
- Species species = referentialService.getSpeciesByReferenceTaxonId(referenceTaxonId);
- target.setSpecies(species);
- }
-
- if (target.getSampleCategoryType() != null && source.getChildBatchs().size() > 0) {
- List<SpeciesBatch> targetChilds = Lists.newArrayList();
- for (Iterator<Batch> iterator = source.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch sourceChild = (SortingBatch) iterator.next();
- SpeciesBatch targetChild = new SpeciesBatch();
- entityToBean(sourceChild, targetChild);
- if (targetChild.getSampleCategoryValue() != null) {
- targetChilds.add(targetChild);
- targetChild.setParentBatch(target);
- }
- }
- target.setChildBatchs(targetChilds);
- }
-
- return target;
- }
-
- @Override
- public SpeciesBatch createSpeciesBatch(SpeciesBatch bean,
- String parentBatchId) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkArgument(bean.getId() == null);
- Preconditions.checkNotNull(bean.getSpecies());
- Preconditions.checkNotNull(bean.getSpecies().getId());
- Preconditions.checkNotNull(bean.getFishingOperation());
- Preconditions.checkNotNull(bean.getFishingOperation().getId());
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- // Load full batch tree
- Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(bean.getFishingOperation().getId()));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- SortingBatch batch = SortingBatch.Factory.newInstance();
- beanToEntity(bean, batch, parentBatchId, catchBatch, true);
- batch = sortingBatchDao.create(batch);
-
- bean.setId(String.valueOf(batch.getId()));
-
- getCurrentSession().flush();
-
- return bean;
- }
-
- @Override
- public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkNotNull(bean.getId());
-
- // Load full batch tree
- Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(bean.getId()));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- SortingBatch batch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(bean.getId()));
- String parentBatchId = null;
- if (bean.getParentBatch() != null) {
- parentBatchId = bean.getParentBatch().getId();
- }
- beanToEntity(bean, batch, parentBatchId, catchBatch, true);
- sortingBatchDao.update(batch);
- getCurrentSession().flush();
-
- return bean;
- }
-
- @Override
- public void deleteSpeciesBatch(String id) {
- Preconditions.checkNotNull(id);
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- catchBatchDao.removeWithChildren(Integer.valueOf(id));
-
- getCurrentSession().flush();
- }
-
- public void deleteSpeciesSubBatch(String id) {
- deleteSpeciesBatch(id);
- }
-
- public void changeSpeciesBatchSpecies(String batchId, Species species) {
- Preconditions.checkNotNull(batchId);
- Preconditions.checkNotNull(species);
- Preconditions.checkNotNull(species.getReferenceTaxonId());
-
- if (log.isDebugEnabled()) {
- log.debug("Changing species for batch id=" + batchId);
- }
-
- int rowUpdated = queryUpdate("updateBatchSpecies",
- "batchId", IntegerType.INSTANCE, Integer.valueOf(batchId),
- "referenceTaxonId", IntegerType.INSTANCE, species.getReferenceTaxonId());
- Preconditions.checkArgument(rowUpdated == 1, "Unable to update operation, to be linked with catch batch.");
- }
-
- public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
- String speciesBatchId) {
- List<SpeciesBatchFrequency> results = Lists.newArrayList();
-
- Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- if (catchBatchId == null) {
- return results;
- }
-
- SortingBatch sortingBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
-
- for (Iterator<Batch> iterator = sortingBatch.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch source = (SortingBatch) iterator.next();
- SpeciesBatchFrequency target = new SpeciesBatchFrequency();
-
- entityToBean(source, target);
- results.add(target);
- }
- return results;
- }
-
- protected void entityToBean(SortingBatch source, SpeciesBatchFrequency target) {
-
- target.setId(source.getId().toString());
-
- target.setNumber(source.getIndividualCount());
- target.setWeight(source.getWeight());
- target.setComment(source.getComments());
-
- // Length step category
- if (source.getSortingMeasurements().size() == 1) {
- SortingMeasurement sm = source.getSortingMeasurements().iterator().next();
- if (sm.getPmfm() != null && sm.getPmfm().getId() != null) {
- Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(sm.getPmfm().getId());
- target.setLengthStepCaracteristic(lengthStepCaracteristic);
- }
-
- // Length
- target.setLengthStep(sm.getNumericalValue());
- }
- }
-
- public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(
- String speciesBatchId, List<SpeciesBatchFrequency> frequencies) {
- Preconditions.checkNotNull(speciesBatchId);
- Preconditions.checkNotNull(frequencies);
-
- if (frequencies.size() == 0) {
- return frequencies;
- }
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
-
- if (catchBatch == null) {
- return frequencies;
- }
-
- // Retrieve parent
- SortingBatch parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
-
- // Remember child ids, to remove unchanged item (see at bottom in this method)
- List<Integer> notUpdatedChildIds = Lists.newArrayList();
- for (Iterator<Batch> iterator = parentBatch.getChildBatchs().iterator(); iterator.hasNext();) {
- SortingBatch sortingBatch = (SortingBatch) iterator.next();
- notUpdatedChildIds.add(sortingBatch.getId());
- }
-
- short rankOrder = 0;
- String pmfmId = null;
- List<SortingBatch> batchsToUpdate = Lists.newArrayList();
- for (SpeciesBatchFrequency source : frequencies) {
- rankOrder++;
-
- // Check that all frequencies have the same length PMFM
- if (pmfmId == null) {
- source.getLengthStepCaracteristic().getId();
- } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) {
- throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic");
- }
-
- // Not existing batch
- SortingBatch target = null;
- if (source.getId() == null) {
- target = SortingBatch.Factory.newInstance();
-
- // Fill the sorting batch from the source
- beanToEntity(source, target, parentBatch, rankOrder, true);
-
- // Create the targeted batch, then update the source id
- sortingBatchDao.create(target);
- source.setId(target.getId().toString());
- }
-
- // Existing batch
- else {
- target = sortingBatchDao.load(Integer.valueOf(source.getId()));
-
- // Fill the sorting batch from the source
- beanToEntity(source, target, parentBatch, rankOrder, true);
-
- // Add the batch into a list (will be update later, using this list)
- batchsToUpdate.add(target);
-
- notUpdatedChildIds.remove(target.getId());
- }
- }
-
- // If some batchs need to be update, do it
- if (batchsToUpdate.size() > 0) {
- sortingBatchDao.update(batchsToUpdate);
- }
-
- if (notUpdatedChildIds.size() > 0) {
- for (Iterator<Integer> iterator = notUpdatedChildIds.iterator(); iterator.hasNext();) {
- Integer batchId = iterator.next();
- catchBatchDao.removeWithChildren(batchId);
- }
- }
-
- getCurrentSession().flush();
-
- return frequencies;
- }
-
- // ------------------------------------------------------------------------//
- // -- Internal methods --//
- // ------------------------------------------------------------------------//
-
- protected void validate(Collection<Batch> batchs, List<CatchBatchValidationError> errors, int treeLevel) {
-
- List<Integer> expectedPmfms = null;
- boolean expectedReferenceTaxon = false;
- // First tree level : should have pmfm SORTED (Vrac, Hors Vrac, Non trié)
- if (treeLevel == 1) {
- expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTED_UNSORTED);
- }
- // Second tree level : should have pmfm SORTING_TYPE (Species, Benthos...)
- else if (treeLevel == 2) {
- expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTING_TYPE);
- }
- else if (treeLevel == 3) {
- expectedReferenceTaxon = true;
- }
- else if (treeLevel > 3) {
- expectedPmfms = referentialService.getSampleCategoryIds();
- expectedPmfms.remove(enumeration.PMFM_ID_SORTED_UNSORTED);
- }
-
- // First level : should be only PMFM=SORTED
- for (Iterator<Batch> iterator = batchs.iterator(); iterator.hasNext();) {
- SortingBatch batch = (SortingBatch) iterator.next();
- boolean batchHasError = false;
-
- // For all sorting measurements
- if (batch.getSortingMeasurements() != null && batch.getSortingMeasurements().size() > 0) {
- for (Iterator<SortingMeasurement> iterator2 = batch.getSortingMeasurements().iterator(); iterator2.hasNext();) {
- SortingMeasurement sm = iterator2.next();
- Integer pmfmId = sm.getPmfm().getId();
- if (expectedReferenceTaxon) {
- CatchBatchValidationError error = new CatchBatchValidationError(
- "tutti.persistence.batch.validation.onlyTaxonButPmfmFound",
- _("tutti.persistence.batch.validation.onlyTaxonButPmfmFound", batch.getId(), pmfmId),
- CatchBatchValidationError.GRAVITY_ERROR);
- errors.add(error);
- }
- else if (expectedPmfms.contains(pmfmId) == false) {
- if (sm.getNumericalValue() == null || batch.getChildBatchs().size() > 0) {
- batchHasError = true;
- CatchBatchValidationError error = new CatchBatchValidationError(
- "tutti.persistence.batch.validation.pmfmNotFound",
- _("tutti.persistence.batch.validation.pmfmNotFound",
- batch.getId(), Arrays.toString(expectedPmfms.toArray()), pmfmId),
- CatchBatchValidationError.GRAVITY_ERROR);
- errors.add(error);
- }
- }
- }
- }
- else if (expectedPmfms != null && expectedPmfms.size() > 0){
- batchHasError = true;
- CatchBatchValidationError error = new CatchBatchValidationError(
- "tutti.persistence.batch.validation.pmfmNotFound",
- _("tutti.persistence.batch.validation.pmfmNotFound",
- batch.getId(), Arrays.toString(expectedPmfms.toArray()), "null"),
- CatchBatchValidationError.GRAVITY_ERROR);
- errors.add(error);
- }
-
- if (!batchHasError && expectedReferenceTaxon == true && batch.getReferenceTaxon() == null) {
- CatchBatchValidationError error = new CatchBatchValidationError(
- "tutti.persistence.batch.validation.referenceTaxonNotFound",
- _("tutti.persistence.batch.validation.referenceTaxonNotFound", batch.getId()),
- CatchBatchValidationError.GRAVITY_ERROR);
- errors.add(error);
- }
-
- if (!batchHasError) {
- validate(batch.getChildBatchs(), errors, treeLevel+1);
- }
- }
- }
-
- protected void beanToEntity(SpeciesBatch source,
- SortingBatch target,
- String parentBatchId,
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch,
- boolean copyIfNull) {
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve recorder department
- Integer recorderDepartmentId = getRecorderDepartmentId();
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // If parent and root need to be set
- if (target.getId() == null
- || target.getRootBatch() == null
- || (target.getParentBatch() != null && !target.getParentBatch().getId().toString().equals(parentBatchId))) {
- setBatchParents(source, target, parentBatchId, catchBatch);
- }
-
- // RankOrder (initialize once, at creation)
- if (target.getRankOrder() == null) {
- // Start rank order at 3, because of special batches 'Biota' and 'Inert'
- short rankOrder = (short) 3;
- if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) {
- // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?)
- rankOrder += (short) source.getParentBatch().getChildBatchs().size();
- }
- target.setRankOrder(rankOrder);
- }
-
- // Force subgroup count to '1', as Allegro
- target.setSubgroupCount(1f);
-
- // Weight or SampleCategoryWeight
- if (copyIfNull && source.getWeight() == null && source.getSampleCategoryWeight() == null) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getSampleCategoryWeight() != null && source.getWeight() == null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sampling Ratio
- if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) {
- String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight();
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight());
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sorting measurement
- if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) {
- Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
- // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch)
- if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
- SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId,
- source.getSampleCategoryType(), source.getSampleCategoryValue());
- notChangedSortingMeasurements.remove(sortingMeasurement);
- }
- }
-
- // Individual count
- if (copyIfNull && source.getNumber() == null) {
- target.setIndividualCount(null);
- } else if (source.getNumber() != null) {
- target.setIndividualCount(source.getNumber());
- }
-
- // Species
- if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) {
- target.setReferenceTaxon(null);
- } else if (source.getSpecies() != null && parentBatchId == null) {
- ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId());
- target.setReferenceTaxon(referenceTaxon);
- }
-
- // QualityFlag
- if (source.isSpeciesToConfirm()) {
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL));
- } else {
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- }
-
- // Comments
- if (copyIfNull && source.getComment() == null) {
- target.setComments(null);
- } else if (source.getComment() != null) {
- target.setComments(source.getComment());
- }
-
- // Exhaustive inventory (always true under a species batch)
- target.setExhaustiveInventory(true);
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- public void setBatchParents(SpeciesBatch source, SortingBatch target, String parentBatchIdStr,
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
-
- Preconditions.checkNotNull(target);
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Load existing parent and root
- SortingBatch parentBatch = null;
- if (parentBatchIdStr != null) {
- parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(parentBatchIdStr));
- }
-
- // Or retrieve parent batch, from pmfm id
- else {
- // Retrieve category type
- Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
- if (pmfmId == null || !pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
- throw new DataIntegrityViolationException(MessageFormat.format(
- "A species batch with no parent should have a sampleCategoryType {0} (PMFM.ID={1})",
- SampleCategoryEnum.sortedUnsorted.name(),
- enumeration.PMFM_ID_SORTED_UNSORTED));
- }
- Integer qualitativeValueId = convertSampleCategoryValueIntoQualitativeId(source.getSampleCategoryValue());
-
- parentBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
- "pmfmId", pmfmId, qualitativeValueId,
- "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
-
- // Parent Batch
- target.setParentBatch(parentBatch);
- }
-
-
- if (parentBatch == null) {
- throw new DataIntegrityViolationException(
- "Could not retrieve parent batch, for a given speciesBatch : invalid batch tree structure. Please make sure CatchBatch has been saved before to create a SpeciesBatch.");
- }
-
- // Parent Batch
- target.setParentBatch(parentBatch);
- target.setRootBatch(catchBatch);
- }
-
- Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) {
- if (value == null)
- return null;
- Integer qualitativeValueId = null;
- if (value instanceof CaracteristicQualitativeValue) {
- CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value;
- qualitativeValueId = Integer.valueOf(cqValue.getId());
- } else if (value instanceof String) {
- qualitativeValueId = Integer.valueOf((String) value);
- }
- return qualitativeValueId;
- }
-
- protected void setSampleCategoryQualitative(SpeciesBatch target, Integer pmfmId, Float numericalvalue, String alphanumericalValue,
- Integer qualitativeValueId) {
- // skip if null or corresponding to the SORTING_TYPE PMFM (Expèce, Benthos, Plancton, etc.)
- if (pmfmId == null || pmfmId.equals(enumeration.PMFM_ID_SORTING_TYPE)) {
- return;
- }
-
- SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
- Preconditions.checkNotNull(sampleCategory, "Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId);
-
- target.setSampleCategoryType(sampleCategory);
- if (numericalvalue != null) {
- target.setSampleCategoryValue(numericalvalue);
- return;
- }
- if (alphanumericalValue != null) {
- target.setSampleCategoryValue(alphanumericalValue);
- return;
- }
-
- Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId);
- if (caracteristic == null || caracteristic.getCaracteristicType() != CaracteristicType.QUALITATIVE) {
- return;
- }
- CaracteristicQualitativeValue value = null;
- for (CaracteristicQualitativeValue qv : caracteristic.getQualitativeValue()) {
- if (qualitativeValueId == Integer.parseInt(qv.getId())) {
- value = qv;
- break;
- }
- }
- target.setSampleCategoryValue(value);
- }
-
- protected void beanToEntity(SpeciesBatchFrequency source, SortingBatch target, SortingBatch parentBatch, short rankOrder, boolean copyIfNull) {
- Preconditions.checkNotNull(source.getBatch());
- Preconditions.checkNotNull(source.getBatch().getId());
-
- // Retrieve recorder department
- Integer recorderDepartmentId = getRecorderDepartmentId();
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // If parent and root need to be set
- if (target.getId() == null
- || target.getRootBatch() == null
- || (target.getParentBatch() != null && !target.getParentBatch().getId().equals(parentBatch.getId()))) {
-
- target.setParentBatch(parentBatch);
- target.setRootBatch(parentBatch.getRootBatch());
- }
-
- // RankOrder
- target.setRankOrder(rankOrder);
-
- // Weight or SampleCategoryWeight
- if (copyIfNull && source.getWeight() == null) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getWeight() != null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sorting measurement
- if (copyIfNull && (source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getLengthStepCaracteristic() != null && source.getLengthStep() != null) {
- Integer pmfmId = Integer.valueOf(source.getLengthStepCaracteristic().getId());
- SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, pmfmId,
- source.getLengthStep());
- notChangedSortingMeasurements.remove(sortingMeasurement);
- }
-
- // Individual count
- if (copyIfNull && source.getNumber() == null) {
- target.setIndividualCount(null);
- } else if (source.getNumber() != null) {
- target.setIndividualCount(source.getNumber());
- }
-
- // Species
- target.setReferenceTaxon(null);
-
- // QualityFlag
- target.setQualityFlag(parentBatch.getQualityFlag());
-
- // Comments
- if (copyIfNull && source.getComment() == null) {
- target.setComments(null);
- } else if (source.getComment() != null) {
- target.setComments(source.getComment());
- }
-
- // Exhaustive inventory (always true under a species batch)
- target.setExhaustiveInventory(true);
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- protected UIWeight convertDatabase2UI(Float weight, Float samplingRatio, String samplingRatioText) {
- UIWeight result = new UIWeight();
-
- // Weight & sampleCategory Weight
- if (samplingRatio == null) {
- result.sampleCategoryWeight = weight;
- } else if (weight != null) {
- String startStr = weight.toString().replace(',', '.') + "/";
- if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
- String weightStr = samplingRatioText.substring(startStr.length());
- if (weightStr != null && !weightStr.isEmpty()) {
- result.sampleCategoryWeight = Float.parseFloat(weightStr);
- result.weight = weight;
- }
- } else {
- result.sampleCategoryWeight = weight;
- }
- }
- return result;
- }
-
- static class UIWeight {
- Float sampleCategoryWeight = null;
-
- Float weight = null;
- }
-
- protected void beanToEntity(CatchBatch source,
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch target,
- boolean copyIfNull) {
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve recorder department
- Integer recorderDepartmentId = getRecorderDepartmentId();
-
- // First initialization (when created)
- Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId());
- target.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId));
-
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRankOrder((short) 1);
- target.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue());
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
-
- // Total Weight
- if (copyIfNull && source.getCatchTotalWeight() == null) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (source.getCatchTotalWeight() != null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getCatchTotalWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- Map<Integer, SortingBatch> catchBatchChilds = getChildsMap(target, enumeration.PMFM_ID_SORTED_UNSORTED);
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac
- // -----------------------------------------------------------------------------
- {
- SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_VRAC_ID);
- if (batch == null) {
- batch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(batch);
- }
- beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
- source.getCatchTotalSortedCarousselWeight(), source.getCatchTotalSortedTremisWeight(),
- copyIfNull);
- batch.setRankOrder((short) 1);
-
- // Manage childs :
- {
- Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac / Species
- // -----------------------------------------------------------------------------
- SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- if (speciesBatch == null) {
- speciesBatch = SortingBatch.Factory.newInstance();
- if (batch.getChildBatchs() == null) {
- batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
- } else {
- batch.getChildBatchs().add(speciesBatch);
- }
- }
- beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
- source.getSpeciesTotalSampleSortedWeight(), source.getSpeciesTotalSortedWeight(),
- copyIfNull);
- speciesBatch.setRankOrder((short) 1);
-
- {
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac / Species / Alive not itemized
- // -----------------------------------------------------------------------------
- SortingBatch aliveNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
- if (aliveNotItemizedBatch == null) {
- aliveNotItemizedBatch = SortingBatch.Factory.newInstance();
- if (speciesBatch.getChildBatchs() == null) {
- speciesBatch.setChildBatchs(Lists.newArrayList((Batch) aliveNotItemizedBatch));
- } else {
- speciesBatch.getChildBatchs().add(aliveNotItemizedBatch);
- }
- }
- beanToEntityReferenceTaxonBatch(target, speciesBatch, aliveNotItemizedBatch, recorderDepartmentId,
- enumeration.REFERENCE_TAXON_ID_LIFE,
- source.getSpeciesTotalLivingNotItemizedWeight(), null,
- copyIfNull);
- aliveNotItemizedBatch.setRankOrder((short) 1);
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac / Species / Inert (not alive)
- // -----------------------------------------------------------------------------
- SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
- if (inertBatch == null) {
- inertBatch = SortingBatch.Factory.newInstance();
- speciesBatch.getChildBatchs().add(inertBatch);
- }
- beanToEntityReferenceTaxonBatch(target, speciesBatch, inertBatch, recorderDepartmentId,
- enumeration.REFERENCE_TAXON_ID_INERT,
- source.getSpeciesTotalInertWeight(), null,
- copyIfNull);
- inertBatch.setRankOrder((short) 2);
- }
- }
- // TODO BL : benthos, plancton, macro déchet...
- }
-
- // -----------------------------------------------------------------------------
- // Sorted Hors Vrac
- // -----------------------------------------------------------------------------
- {
- SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_HORS_VRAC_ID);
- if (batch == null) {
- batch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(batch);
- }
- beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
- source.getCatchTotalUnsortedWeight(), null,
- copyIfNull);
- batch.setRankOrder((short) 2);
-
- // Manage childs :
- {
- Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
-
- // Species :
- SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- if (speciesBatch == null) {
- speciesBatch = SortingBatch.Factory.newInstance();
- if (batch.getChildBatchs() == null) {
- batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
- } else {
- batch.getChildBatchs().add(speciesBatch);
- }
- }
- beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
- source.getSpeciesTotalUnsortedWeight(), null,
- copyIfNull);
- speciesBatch.setRankOrder((short) 1);
- }
-
- // TODO BL : benthos, plancton, macro déchet...
- }
-
- // -----------------------------------------------------------------------------
- // Unsorted (=rejected)
- // -----------------------------------------------------------------------------
- // Unsorted :
- SortingBatch unsortedBatch = catchBatchChilds.get(enumeration.QUALITATIVE_UNSORTED_ID);
- if (unsortedBatch == null) {
- unsortedBatch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(unsortedBatch);
- }
- beanToEntitySortingBatch(target, target, unsortedBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID,
- source.getCatchTotalRejectedWeight(), null,
- copyIfNull);
- unsortedBatch.setRankOrder((short) 3);
-
- }
-
- protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) {
- Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
- if (parentBatch.getChildBatchs() == null) {
- return batchByQualitativeValueId;
- }
- for (Batch childBatch : parentBatch.getChildBatchs()) {
- SortingBatch childSortingBatch = (SortingBatch) childBatch;
- SortingMeasurement sm = measurementHelper.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false);
- if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) {
- batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), childSortingBatch);
- }
- }
- return batchByQualitativeValueId;
- }
-
- /**
- * Retrieve child batchs if species is "Life" or "No life"
- * (need to retrieve: speciesTotalLivingNotItemizedWeight and speciesTotalInertWeight)
- *
- * @param parentBatch
- * @return
- */
- protected Map<Integer, SortingBatch> getChildAliveNotSortedOrInert(Batch parentBatch) {
- Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
- if (parentBatch.getChildBatchs() == null) {
- return batchByQualitativeValueId;
- }
- for (Batch childBatch : parentBatch.getChildBatchs()) {
- SortingBatch childSortingBatch = (SortingBatch) childBatch;
- if (childSortingBatch.getReferenceTaxon() != null && childSortingBatch.getId().intValue() < 0) {
- if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
- batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
- } else if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
- batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
- }
- }
- }
- return batchByQualitativeValueId;
- }
-
- protected void beanToEntitySortingBatch(
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
- fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
- fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
- Integer recorderDepartmentId,
- Integer sortingPmfmId,
- Integer sortingQualitativeValueId,
- Float weight,
- Float sampleWeight,
- boolean copyIfNull) {
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // Some mandatory properties :
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRootBatch(rootBatch);
- target.setParentBatch(parentBatch);
- target.setExhaustiveInventory(true);
-
- // No taxon or taxon group
- target.setReferenceTaxon(null);
- target.setTaxonGroup(null);
-
- // Sorting measurement
- if (copyIfNull && (sortingPmfmId == null || sortingQualitativeValueId == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (sortingPmfmId != null && sortingQualitativeValueId != null) {
- SortingMeasurement sm = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId);
- notChangedSortingMeasurements.remove(sm);
- }
-
- // Sampling Ratio
- if (copyIfNull && (sampleWeight == null || weight == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (sampleWeight != null && weight != null) {
- String samplingRatioText = weight + "/" + sampleWeight;
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(weight / sampleWeight);
- }
-
- // Weight
- if (copyIfNull && (sampleWeight == null && weight == null)) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (sampleWeight != null || weight != null) {
- Float batchReferenceWeight = weight;
- if (batchReferenceWeight == null) {
- batchReferenceWeight = sampleWeight;
- }
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- protected void beanToEntityReferenceTaxonBatch(
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
- fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
- fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
- Integer recorderDepartmentId,
- Integer referenceTaxonId,
- Float weight,
- Float sampleWeight,
- boolean copyIfNull) {
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // Some mandatory properties :
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRootBatch(rootBatch);
- target.setParentBatch(parentBatch);
- target.setExhaustiveInventory(true);
-
- // Reference taxon
- target.setReferenceTaxon(load(ReferenceTaxonImpl.class, referenceTaxonId));
- target.setTaxonGroup(null);
-
- // Sampling Ratio
- if (copyIfNull && (sampleWeight == null || weight == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (sampleWeight != null && weight != null) {
- String samplingRatioText = weight + "/" + sampleWeight;
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(weight / sampleWeight);
- }
-
- // Weight
- if (copyIfNull && (sampleWeight == null && weight == null)) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (sampleWeight != null || weight != null) {
- Float batchReferenceWeight = weight;
- if (batchReferenceWeight == null) {
- batchReferenceWeight = sampleWeight;
- }
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
- enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- protected Integer getRecorderDepartmentId() {
- // TODO BL : voir si on peut récupérer le departement (du 1er saisisseur ?)
- return enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
- }
-}
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.Serializable;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.annotation.Resource;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.FlushMode;
+import org.hibernate.type.IntegerType;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.DataRetrievalFailureException;
+import org.springframework.stereotype.Service;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+import fr.ifremer.adagio.core.dao.data.batch.Batch;
+import fr.ifremer.adagio.core.dao.data.batch.CatchBatchExtendDao;
+import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
+import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
+import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationError;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidator;
+import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
+import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
+import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
+import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
+import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
+import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
+import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
+import fr.ifremer.tutti.persistence.entities.referential.Species;
+import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
+
+@Service("batchPersistenceService")
+public class BatchPersistenceServiceImpl
+ extends AbstractPersistenceService implements BatchPersistenceService, CatchBatchValidator
+ {
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(BatchPersistenceServiceImpl.class);
+
+ @Resource(name = "referentialPersistenceService")
+ protected ReferentialPersistenceService referentialService;
+
+ @Resource(name = "denormalizedBatchDao")
+ protected DenormalizedBatchDao denormalizedBatchDao;
+
+ @Resource(name = "sortingBatchDao")
+ protected SortingBatchDao sortingBatchDao;
+
+ @Resource(name = "catchBatchDao")
+ protected CatchBatchExtendDao catchBatchDao;
+
+ @Resource(name = "measurementPersistenceHelper")
+ protected MeasurementPersistenceHelper measurementHelper;
+
+ @Override
+ public void init() {
+ super.init();
+ catchBatchDao.registerCatchBatchValidator(this);
+ }
+
+ @Override
+ public void close() {
+ catchBatchDao.unregisterCatchBatchValidator(this);
+ super.close();
+ }
+
+ @Override
+ public boolean isEnable(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+ // Apply validation only on catch batch for fishingOperation
+ return (catchBatch.getFishingOperation() != null);
+ }
+
+ @Override
+ public List<CatchBatchValidationError> validate(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+ List<CatchBatchValidationError> errors = Lists.newArrayList();
+ validate(catchBatch.getChildBatchs(), errors, 1);
+ return errors;
+ }
+
+ @Override
+ public CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) {
+ Preconditions.checkNotNull(fishingOperationId);
+
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
+
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch source;
+ try {
+ source = catchBatchDao.loadFullTree(catchBatchId, true, true);
+ } catch (CatchBatchValidationException e) {
+ throw new DataRetrievalFailureException("Invalid batch tree structure, for fishing operation id=" + fishingOperationId, e);
+ }
+
+ CatchBatch result = new CatchBatch();
+ result.setId(source.getId().toString());
+ result.setCatchTotalWeight(source.getWeight());
+
+ // Vrac
+ SortingBatch vracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID);
+ result.setCatchTotalSortedCarousselWeight(vracBatch.getWeight());
+ result.setCatchTotalSortedTremisWeight(vracBatch.getWeightBeforeSampling());
+ {
+ // Species
+ SortingBatch speciesBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ result.setSpeciesTotalSampleSortedWeight(speciesBatch.getWeight());
+ result.setSpeciesTotalSortedWeight(speciesBatch.getWeightBeforeSampling());
+
+ {
+ // Inert
+ SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
+ "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
+ result.setSpeciesTotalInertWeight(inertBatch.getWeight());
+
+ // Alive no itemized
+ SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
+ "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
+ result.setSpeciesTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight());
+ }
+
+ // TODO : Benthos, Plancton...
+ }
+
+ // Hors Vrac
+ SortingBatch horsVracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID);
+ result.setCatchTotalUnsortedWeight(horsVracBatch.getWeight());
+ {
+ // Species
+ SortingBatch speciesBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ result.setSpeciesTotalUnsortedWeight(speciesBatch.getWeight());
+
+ // TODO : Benthos, Plancton...
+ }
+
+ // Non trié
+ SortingBatch unsortedBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID);
+ result.setCatchTotalRejectedWeight(unsortedBatch.getWeight());
+
+ return result;
+ }
+
+ @Override
+
+ public CatchBatch createCatchBatch(CatchBatch bean) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkArgument(bean.getId() == null);
+ Preconditions.checkNotNull(bean.getFishingOperation());
+ Preconditions.checkNotNull(bean.getFishingOperation().getId());
+
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = fr.ifremer.adagio.core.dao.data.batch.CatchBatch.Factory.newInstance();
+ beanToEntity(bean, catchBatch, true);
+ catchBatch = catchBatchDao.create(catchBatch);
+ bean.setId(String.valueOf(catchBatch.getId()));
+
+ // Link to fishing operation
+ getCurrentSession().flush();
+ Integer fishingOperationId = Integer.valueOf(bean.getFishingOperation().getId());
+ int rowUpdated = queryUpdate("updateFishingOperationCatchBatch",
+ "fishingOperationId", IntegerType.INSTANCE, fishingOperationId,
+ "catchBatchId", IntegerType.INSTANCE, catchBatch.getId());
+ if (rowUpdated == 0) {
+ throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found.");
+ }
+
+ return bean;
+ }
+
+ @Override
+ @CacheEvict(value = "batchTree", key="#bean.fishingOperation.id")
+ public CatchBatch saveCatchBatch(CatchBatch bean) {
+
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkNotNull(bean.getId());
+
+ getCurrentSession().enableFetchProfile("batch-with-childs");
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(Integer.valueOf(bean.getId()));
+ if (catchBatch == null) {
+ throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId());
+ }
+
+ beanToEntity(bean, catchBatch, true);
+ catchBatchDao.update(catchBatch);
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) {
+
+ // Load batch tree
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ List<SpeciesBatch> result = new ArrayList<SpeciesBatch>();
+
+ // Vrac / Species
+ SortingBatch vracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ for (Iterator<Batch> iterator = vracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+
+ // evict some special batches : Life (or Biota) and Inert
+ if (source.getReferenceTaxon() != null
+ && enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) == false
+ && enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId()) == false) {
+ SpeciesBatch target = new SpeciesBatch();
+
+ entityToBean(source, target);
+ result.add(target);
+ }
+ }
+
+ // Hors-Vrac / Species
+ SortingBatch horsVracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ for (Iterator<Batch> iterator = horsVracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+
+ SpeciesBatch target = new SpeciesBatch();
+
+ entityToBean(source, target);
+ result.add(target);
+ }
+
+ return result;
+ }
+
+ protected SpeciesBatch entityToBean(SortingBatch source, SpeciesBatch target) {
+
+ target.setId(source.getId().toString());
+
+ // Individual count
+ target.setNumber(source.getIndividualCount());
+
+ // Convert database weight (and sampling ratio) into UI weight and sampleCategoryWeight
+ if (source.getWeight() != null && source.getWeightBeforeSampling() == null) {
+ target.setSampleCategoryWeight(source.getWeight());
+ }
+ else {
+ target.setWeight(source.getWeight());
+ target.setSampleCategoryWeight(source.getWeightBeforeSampling());
+ }
+
+ // Comments
+ target.setComment(source.getComments());
+
+ // Sample category type (only one is applied)
+ SortingMeasurement sm = null;
+ if (source.getSortingMeasurements().size() == 1) {
+ sm = source.getSortingMeasurements().iterator().next();
+ }
+ else if (source.getReferenceTaxon() != null && source.getReferenceTaxon().getId() != null){
+ sm = measurementHelper.getInheritedSortingMeasurement(source, enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+ if (sm != null) {
+ SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(sm.getPmfm().getId());
+ if (sampleCategory != null) {
+ setSampleCategoryQualitative(target, sm.getPmfm().getId(), sm.getNumericalValue(), sm.getAlphanumericalValue(), sm.getQualitativeValue().getId());
+ }
+ }
+
+ // Species
+ Integer referenceTaxonId = source.getInheritedReferenceTaxonId();
+ if (referenceTaxonId == null && source.getReferenceTaxon() != null) {
+ referenceTaxonId = source.getReferenceTaxon().getId();
+ }
+ if (referenceTaxonId != null) {
+ // TODO : add cache on getSpeciesByReferenceTaxonId
+ Species species = referentialService.getSpeciesByReferenceTaxonId(referenceTaxonId);
+ target.setSpecies(species);
+ }
+
+ if (target.getSampleCategoryType() != null && source.getChildBatchs().size() > 0) {
+ List<SpeciesBatch> targetChilds = Lists.newArrayList();
+ for (Iterator<Batch> iterator = source.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch sourceChild = (SortingBatch) iterator.next();
+ SpeciesBatch targetChild = new SpeciesBatch();
+ entityToBean(sourceChild, targetChild);
+ if (targetChild.getSampleCategoryValue() != null) {
+ targetChilds.add(targetChild);
+ targetChild.setParentBatch(target);
+ }
+ }
+ target.setChildBatchs(targetChilds);
+ }
+
+ return target;
+ }
+
+ @Override
+ public SpeciesBatch createSpeciesBatch(SpeciesBatch bean,
+ String parentBatchId) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkArgument(bean.getId() == null);
+ Preconditions.checkNotNull(bean.getSpecies());
+ Preconditions.checkNotNull(bean.getSpecies().getId());
+ Preconditions.checkNotNull(bean.getFishingOperation());
+ Preconditions.checkNotNull(bean.getFishingOperation().getId());
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ // Load full batch tree
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(bean.getFishingOperation().getId()));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ SortingBatch batch = SortingBatch.Factory.newInstance();
+ beanToEntity(bean, batch, parentBatchId, catchBatch, true);
+ batch = sortingBatchDao.create(batch);
+
+ bean.setId(String.valueOf(batch.getId()));
+
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkNotNull(bean.getId());
+
+ // Load full batch tree
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(bean.getId()));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ SortingBatch batch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(bean.getId()));
+ String parentBatchId = null;
+ if (bean.getParentBatch() != null) {
+ parentBatchId = bean.getParentBatch().getId();
+ }
+ beanToEntity(bean, batch, parentBatchId, catchBatch, true);
+ sortingBatchDao.update(batch);
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public void deleteSpeciesBatch(String id) {
+ Preconditions.checkNotNull(id);
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ catchBatchDao.removeWithChildren(Integer.valueOf(id));
+
+ getCurrentSession().flush();
+ }
+
+ public void deleteSpeciesSubBatch(String id) {
+ deleteSpeciesBatch(id);
+ }
+
+ public void changeSpeciesBatchSpecies(String batchId, Species species) {
+ Preconditions.checkNotNull(batchId);
+ Preconditions.checkNotNull(species);
+ Preconditions.checkNotNull(species.getReferenceTaxonId());
+
+ if (log.isDebugEnabled()) {
+ log.debug("Changing species for batch id=" + batchId);
+ }
+
+ int rowUpdated = queryUpdate("updateBatchSpecies",
+ "batchId", IntegerType.INSTANCE, Integer.valueOf(batchId),
+ "referenceTaxonId", IntegerType.INSTANCE, species.getReferenceTaxonId());
+ Preconditions.checkArgument(rowUpdated == 1, "Unable to update operation, to be linked with catch batch.");
+ }
+
+ public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
+ String speciesBatchId) {
+ List<SpeciesBatchFrequency> results = Lists.newArrayList();
+
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ if (catchBatchId == null) {
+ return results;
+ }
+
+ SortingBatch sortingBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
+
+ for (Iterator<Batch> iterator = sortingBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+ SpeciesBatchFrequency target = new SpeciesBatchFrequency();
+
+ entityToBean(source, target);
+ results.add(target);
+ }
+ return results;
+ }
+
+ protected void entityToBean(SortingBatch source, SpeciesBatchFrequency target) {
+
+ target.setId(source.getId().toString());
+
+ target.setNumber(source.getIndividualCount());
+ target.setWeight(source.getWeight());
+ target.setComment(source.getComments());
+
+ // Length step category
+ if (source.getSortingMeasurements().size() == 1) {
+ SortingMeasurement sm = source.getSortingMeasurements().iterator().next();
+ if (sm.getPmfm() != null && sm.getPmfm().getId() != null) {
+ Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(sm.getPmfm().getId());
+ target.setLengthStepCaracteristic(lengthStepCaracteristic);
+ }
+
+ // Length
+ target.setLengthStep(sm.getNumericalValue());
+ }
+ }
+
+ public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(
+ String speciesBatchId, List<SpeciesBatchFrequency> frequencies) {
+ Preconditions.checkNotNull(speciesBatchId);
+ Preconditions.checkNotNull(frequencies);
+
+ if (frequencies.size() == 0) {
+ return frequencies;
+ }
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ if (catchBatch == null) {
+ return frequencies;
+ }
+
+ // Retrieve parent
+ SortingBatch parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
+
+ // Remember child ids, to remove unchanged item (see at bottom in this method)
+ List<Integer> notUpdatedChildIds = Lists.newArrayList();
+ for (Iterator<Batch> iterator = parentBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch sortingBatch = (SortingBatch) iterator.next();
+ notUpdatedChildIds.add(sortingBatch.getId());
+ }
+
+ short rankOrder = 0;
+ String pmfmId = null;
+ List<SortingBatch> batchsToUpdate = Lists.newArrayList();
+ for (SpeciesBatchFrequency source : frequencies) {
+ rankOrder++;
+
+ // Check that all frequencies have the same length PMFM
+ if (pmfmId == null) {
+ source.getLengthStepCaracteristic().getId();
+ } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) {
+ throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic");
+ }
+
+ // Not existing batch
+ SortingBatch target = null;
+ if (source.getId() == null) {
+ target = SortingBatch.Factory.newInstance();
+
+ // Fill the sorting batch from the source
+ beanToEntity(source, target, parentBatch, rankOrder, true);
+
+ // Create the targeted batch, then update the source id
+ sortingBatchDao.create(target);
+ source.setId(target.getId().toString());
+ }
+
+ // Existing batch
+ else {
+ target = sortingBatchDao.load(Integer.valueOf(source.getId()));
+
+ // Fill the sorting batch from the source
+ beanToEntity(source, target, parentBatch, rankOrder, true);
+
+ // Add the batch into a list (will be update later, using this list)
+ batchsToUpdate.add(target);
+
+ notUpdatedChildIds.remove(target.getId());
+ }
+ }
+
+ // If some batchs need to be update, do it
+ if (batchsToUpdate.size() > 0) {
+ sortingBatchDao.update(batchsToUpdate);
+ }
+
+ if (notUpdatedChildIds.size() > 0) {
+ for (Iterator<Integer> iterator = notUpdatedChildIds.iterator(); iterator.hasNext();) {
+ Integer batchId = iterator.next();
+ catchBatchDao.removeWithChildren(batchId);
+ }
+ }
+
+ getCurrentSession().flush();
+
+ return frequencies;
+ }
+
+ // ------------------------------------------------------------------------//
+ // -- Internal methods --//
+ // ------------------------------------------------------------------------//
+
+ protected void validate(Collection<Batch> batchs, List<CatchBatchValidationError> errors, int treeLevel) {
+
+ List<Integer> expectedPmfms = null;
+ boolean expectedReferenceTaxon = false;
+ // First tree level : should have pmfm SORTED (Vrac, Hors Vrac, Non trié)
+ if (treeLevel == 1) {
+ expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+ // Second tree level : should have pmfm SORTING_TYPE (Species, Benthos...)
+ else if (treeLevel == 2) {
+ expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTING_TYPE);
+ }
+ else if (treeLevel == 3) {
+ expectedReferenceTaxon = true;
+ }
+ else if (treeLevel > 3) {
+ expectedPmfms = referentialService.getSampleCategoryIds();
+ expectedPmfms.remove(enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+
+ // First level : should be only PMFM=SORTED
+ for (Iterator<Batch> iterator = batchs.iterator(); iterator.hasNext();) {
+ SortingBatch batch = (SortingBatch) iterator.next();
+ boolean batchHasError = false;
+
+ // For all sorting measurements
+ if (batch.getSortingMeasurements() != null && batch.getSortingMeasurements().size() > 0) {
+ for (Iterator<SortingMeasurement> iterator2 = batch.getSortingMeasurements().iterator(); iterator2.hasNext();) {
+ SortingMeasurement sm = iterator2.next();
+ Integer pmfmId = sm.getPmfm().getId();
+ if (expectedReferenceTaxon) {
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.onlyTaxonButPmfmFound",
+ _("tutti.persistence.batch.validation.onlyTaxonButPmfmFound", batch.getId(), pmfmId),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+ else if (expectedPmfms.contains(pmfmId) == false) {
+ if (sm.getNumericalValue() == null || batch.getChildBatchs().size() > 0) {
+ batchHasError = true;
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.pmfmNotFound",
+ _("tutti.persistence.batch.validation.pmfmNotFound",
+ batch.getId(), Arrays.toString(expectedPmfms.toArray()), pmfmId),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+ }
+ }
+ }
+ else if (expectedPmfms != null && expectedPmfms.size() > 0){
+ batchHasError = true;
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.pmfmNotFound",
+ _("tutti.persistence.batch.validation.pmfmNotFound",
+ batch.getId(), Arrays.toString(expectedPmfms.toArray()), "null"),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+
+ if (!batchHasError && expectedReferenceTaxon == true && batch.getReferenceTaxon() == null) {
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.referenceTaxonNotFound",
+ _("tutti.persistence.batch.validation.referenceTaxonNotFound", batch.getId()),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+
+ if (!batchHasError) {
+ validate(batch.getChildBatchs(), errors, treeLevel+1);
+ }
+ }
+ }
+
+ protected void beanToEntity(SpeciesBatch source,
+ SortingBatch target,
+ String parentBatchId,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch,
+ boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // If parent and root need to be set
+ if (target.getId() == null
+ || target.getRootBatch() == null
+ || (target.getParentBatch() != null && !target.getParentBatch().getId().toString().equals(parentBatchId))) {
+ setBatchParents(source, target, parentBatchId, catchBatch);
+ }
+
+ // RankOrder (initialize once, at creation)
+ if (target.getRankOrder() == null) {
+ // Start rank order at 3, because of special batches 'Biota' and 'Inert'
+ short rankOrder = (short) 3;
+ if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) {
+ // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?)
+ rankOrder += (short) source.getParentBatch().getChildBatchs().size();
+ }
+ target.setRankOrder(rankOrder);
+ }
+
+ // Force subgroup count to '1', as Allegro
+ target.setSubgroupCount(1f);
+
+ // Weight or SampleCategoryWeight
+ if (copyIfNull && source.getWeight() == null && source.getSampleCategoryWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getSampleCategoryWeight() != null && source.getWeight() == null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sampling Ratio
+ if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) {
+ String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight();
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight());
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sorting measurement
+ if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) {
+ Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
+ // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch)
+ if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
+ SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId,
+ source.getSampleCategoryType(), source.getSampleCategoryValue());
+ notChangedSortingMeasurements.remove(sortingMeasurement);
+ }
+ }
+
+ // Individual count
+ if (copyIfNull && source.getNumber() == null) {
+ target.setIndividualCount(null);
+ } else if (source.getNumber() != null) {
+ target.setIndividualCount(source.getNumber());
+ }
+
+ // Species
+ if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) {
+ target.setReferenceTaxon(null);
+ } else if (source.getSpecies() != null && parentBatchId == null) {
+ ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId());
+ target.setReferenceTaxon(referenceTaxon);
+ }
+
+ // QualityFlag
+ if (source.isSpeciesToConfirm()) {
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL));
+ } else {
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ }
+
+ // Comments
+ if (copyIfNull && source.getComment() == null) {
+ target.setComments(null);
+ } else if (source.getComment() != null) {
+ target.setComments(source.getComment());
+ }
+
+ // Exhaustive inventory (always true under a species batch)
+ target.setExhaustiveInventory(true);
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ public void setBatchParents(SpeciesBatch source, SortingBatch target, String parentBatchIdStr,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+
+ Preconditions.checkNotNull(target);
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Load existing parent and root
+ SortingBatch parentBatch = null;
+ if (parentBatchIdStr != null) {
+ parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(parentBatchIdStr));
+ }
+
+ // Or retrieve parent batch, from pmfm id
+ else {
+ // Retrieve category type
+ Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
+ if (pmfmId == null || !pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
+ throw new DataIntegrityViolationException(MessageFormat.format(
+ "A species batch with no parent should have a sampleCategoryType {0} (PMFM.ID={1})",
+ SampleCategoryEnum.sortedUnsorted.name(),
+ enumeration.PMFM_ID_SORTED_UNSORTED));
+ }
+ Integer qualitativeValueId = convertSampleCategoryValueIntoQualitativeId(source.getSampleCategoryValue());
+
+ parentBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", pmfmId, qualitativeValueId,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ // Parent Batch
+ target.setParentBatch(parentBatch);
+ }
+
+
+ if (parentBatch == null) {
+ throw new DataIntegrityViolationException(
+ "Could not retrieve parent batch, for a given speciesBatch : invalid batch tree structure. Please make sure CatchBatch has been saved before to create a SpeciesBatch.");
+ }
+
+ // Parent Batch
+ target.setParentBatch(parentBatch);
+ target.setRootBatch(catchBatch);
+ }
+
+ Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) {
+ if (value == null)
+ return null;
+ Integer qualitativeValueId = null;
+ if (value instanceof CaracteristicQualitativeValue) {
+ CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value;
+ qualitativeValueId = Integer.valueOf(cqValue.getId());
+ } else if (value instanceof String) {
+ qualitativeValueId = Integer.valueOf((String) value);
+ }
+ return qualitativeValueId;
+ }
+
+ protected void setSampleCategoryQualitative(SpeciesBatch target, Integer pmfmId, Float numericalvalue, String alphanumericalValue,
+ Integer qualitativeValueId) {
+ // skip if null or corresponding to the SORTING_TYPE PMFM (Expèce, Benthos, Plancton, etc.)
+ if (pmfmId == null || pmfmId.equals(enumeration.PMFM_ID_SORTING_TYPE)) {
+ return;
+ }
+
+ SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
+ Preconditions.checkNotNull(sampleCategory, "Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId);
+
+ target.setSampleCategoryType(sampleCategory);
+ if (numericalvalue != null) {
+ target.setSampleCategoryValue(numericalvalue);
+ return;
+ }
+ if (alphanumericalValue != null) {
+ target.setSampleCategoryValue(alphanumericalValue);
+ return;
+ }
+
+ Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId);
+ if (caracteristic == null || caracteristic.getCaracteristicType() != CaracteristicType.QUALITATIVE) {
+ return;
+ }
+ CaracteristicQualitativeValue value = null;
+ for (CaracteristicQualitativeValue qv : caracteristic.getQualitativeValue()) {
+ if (qualitativeValueId == Integer.parseInt(qv.getId())) {
+ value = qv;
+ break;
+ }
+ }
+ target.setSampleCategoryValue(value);
+ }
+
+ protected void beanToEntity(SpeciesBatchFrequency source, SortingBatch target, SortingBatch parentBatch, short rankOrder, boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getBatch());
+ Preconditions.checkNotNull(source.getBatch().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // If parent and root need to be set
+ if (target.getId() == null
+ || target.getRootBatch() == null
+ || (target.getParentBatch() != null && !target.getParentBatch().getId().equals(parentBatch.getId()))) {
+
+ target.setParentBatch(parentBatch);
+ target.setRootBatch(parentBatch.getRootBatch());
+ }
+
+ // RankOrder
+ target.setRankOrder(rankOrder);
+
+ // Weight or SampleCategoryWeight
+ if (copyIfNull && source.getWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getWeight() != null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sorting measurement
+ if (copyIfNull && (source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getLengthStepCaracteristic() != null && source.getLengthStep() != null) {
+ Integer pmfmId = Integer.valueOf(source.getLengthStepCaracteristic().getId());
+ SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, pmfmId,
+ source.getLengthStep());
+ notChangedSortingMeasurements.remove(sortingMeasurement);
+ }
+
+ // Individual count
+ if (copyIfNull && source.getNumber() == null) {
+ target.setIndividualCount(null);
+ } else if (source.getNumber() != null) {
+ target.setIndividualCount(source.getNumber());
+ }
+
+ // Species
+ target.setReferenceTaxon(null);
+
+ // QualityFlag
+ target.setQualityFlag(parentBatch.getQualityFlag());
+
+ // Comments
+ if (copyIfNull && source.getComment() == null) {
+ target.setComments(null);
+ } else if (source.getComment() != null) {
+ target.setComments(source.getComment());
+ }
+
+ // Exhaustive inventory (always true under a species batch)
+ target.setExhaustiveInventory(true);
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected UIWeight convertDatabase2UI(Float weight, Float samplingRatio, String samplingRatioText) {
+ UIWeight result = new UIWeight();
+
+ // Weight & sampleCategory Weight
+ if (samplingRatio == null) {
+ result.sampleCategoryWeight = weight;
+ } else if (weight != null) {
+ String startStr = weight.toString().replace(',', '.') + "/";
+ if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
+ String weightStr = samplingRatioText.substring(startStr.length());
+ if (weightStr != null && !weightStr.isEmpty()) {
+ result.sampleCategoryWeight = Float.parseFloat(weightStr);
+ result.weight = weight;
+ }
+ } else {
+ result.sampleCategoryWeight = weight;
+ }
+ }
+ return result;
+ }
+
+ static class UIWeight {
+ Float sampleCategoryWeight = null;
+
+ Float weight = null;
+ }
+
+ protected void beanToEntity(CatchBatch source,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch target,
+ boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // First initialization (when created)
+ Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId());
+ target.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId));
+
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRankOrder((short) 1);
+ target.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue());
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+
+ // Total Weight
+ if (copyIfNull && source.getCatchTotalWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (source.getCatchTotalWeight() != null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getCatchTotalWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ Map<Integer, SortingBatch> catchBatchChilds = getChildsMap(target, enumeration.PMFM_ID_SORTED_UNSORTED);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac
+ // -----------------------------------------------------------------------------
+ {
+ SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_VRAC_ID);
+ if (batch == null) {
+ batch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(batch);
+ }
+ beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
+ source.getCatchTotalSortedCarousselWeight(), source.getCatchTotalSortedTremisWeight(),
+ copyIfNull);
+ batch.setRankOrder((short) 1);
+
+ // Manage childs :
+ {
+ Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species
+ // -----------------------------------------------------------------------------
+ SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ if (speciesBatch == null) {
+ speciesBatch = SortingBatch.Factory.newInstance();
+ if (batch.getChildBatchs() == null) {
+ batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
+ } else {
+ batch.getChildBatchs().add(speciesBatch);
+ }
+ }
+ beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
+ source.getSpeciesTotalSampleSortedWeight(), source.getSpeciesTotalSortedWeight(),
+ copyIfNull);
+ speciesBatch.setRankOrder((short) 1);
+
+ {
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species / Alive not itemized
+ // -----------------------------------------------------------------------------
+ SortingBatch aliveNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
+ if (aliveNotItemizedBatch == null) {
+ aliveNotItemizedBatch = SortingBatch.Factory.newInstance();
+ if (speciesBatch.getChildBatchs() == null) {
+ speciesBatch.setChildBatchs(Lists.newArrayList((Batch) aliveNotItemizedBatch));
+ } else {
+ speciesBatch.getChildBatchs().add(aliveNotItemizedBatch);
+ }
+ }
+ beanToEntityReferenceTaxonBatch(target, speciesBatch, aliveNotItemizedBatch, recorderDepartmentId,
+ enumeration.REFERENCE_TAXON_ID_LIFE,
+ source.getSpeciesTotalLivingNotItemizedWeight(), null,
+ copyIfNull);
+ aliveNotItemizedBatch.setRankOrder((short) 1);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species / Inert (not alive)
+ // -----------------------------------------------------------------------------
+ SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
+ if (inertBatch == null) {
+ inertBatch = SortingBatch.Factory.newInstance();
+ speciesBatch.getChildBatchs().add(inertBatch);
+ }
+ beanToEntityReferenceTaxonBatch(target, speciesBatch, inertBatch, recorderDepartmentId,
+ enumeration.REFERENCE_TAXON_ID_INERT,
+ source.getSpeciesTotalInertWeight(), null,
+ copyIfNull);
+ inertBatch.setRankOrder((short) 2);
+ }
+ }
+ // TODO BL : benthos, plancton, macro déchet...
+ }
+
+ // -----------------------------------------------------------------------------
+ // Sorted Hors Vrac
+ // -----------------------------------------------------------------------------
+ {
+ SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_HORS_VRAC_ID);
+ if (batch == null) {
+ batch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(batch);
+ }
+ beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
+ source.getCatchTotalUnsortedWeight(), null,
+ copyIfNull);
+ batch.setRankOrder((short) 2);
+
+ // Manage childs :
+ {
+ Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
+
+ // Species :
+ SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ if (speciesBatch == null) {
+ speciesBatch = SortingBatch.Factory.newInstance();
+ if (batch.getChildBatchs() == null) {
+ batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
+ } else {
+ batch.getChildBatchs().add(speciesBatch);
+ }
+ }
+ beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
+ source.getSpeciesTotalUnsortedWeight(), null,
+ copyIfNull);
+ speciesBatch.setRankOrder((short) 1);
+ }
+
+ // TODO BL : benthos, plancton, macro déchet...
+ }
+
+ // -----------------------------------------------------------------------------
+ // Unsorted (=rejected)
+ // -----------------------------------------------------------------------------
+ // Unsorted :
+ SortingBatch unsortedBatch = catchBatchChilds.get(enumeration.QUALITATIVE_UNSORTED_ID);
+ if (unsortedBatch == null) {
+ unsortedBatch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(unsortedBatch);
+ }
+ beanToEntitySortingBatch(target, target, unsortedBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID,
+ source.getCatchTotalRejectedWeight(), null,
+ copyIfNull);
+ unsortedBatch.setRankOrder((short) 3);
+
+ }
+
+ protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) {
+ Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
+ if (parentBatch.getChildBatchs() == null) {
+ return batchByQualitativeValueId;
+ }
+ for (Batch childBatch : parentBatch.getChildBatchs()) {
+ SortingBatch childSortingBatch = (SortingBatch) childBatch;
+ SortingMeasurement sm = measurementHelper.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false);
+ if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) {
+ batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), childSortingBatch);
+ }
+ }
+ return batchByQualitativeValueId;
+ }
+
+ /**
+ * Retrieve child batchs if species is "Life" or "No life"
+ * (need to retrieve: speciesTotalLivingNotItemizedWeight and speciesTotalInertWeight)
+ *
+ * @param parentBatch
+ * @return
+ */
+ protected Map<Integer, SortingBatch> getChildAliveNotSortedOrInert(Batch parentBatch) {
+ Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
+ if (parentBatch.getChildBatchs() == null) {
+ return batchByQualitativeValueId;
+ }
+ for (Batch childBatch : parentBatch.getChildBatchs()) {
+ SortingBatch childSortingBatch = (SortingBatch) childBatch;
+ if (childSortingBatch.getReferenceTaxon() != null && childSortingBatch.getId().intValue() < 0) {
+ if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
+ batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
+ } else if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
+ batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
+ }
+ }
+ }
+ return batchByQualitativeValueId;
+ }
+
+ protected void beanToEntitySortingBatch(
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
+ fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
+ fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
+ Integer recorderDepartmentId,
+ Integer sortingPmfmId,
+ Integer sortingQualitativeValueId,
+ Float weight,
+ Float sampleWeight,
+ boolean copyIfNull) {
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // Some mandatory properties :
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRootBatch(rootBatch);
+ target.setParentBatch(parentBatch);
+ target.setExhaustiveInventory(true);
+
+ // No taxon or taxon group
+ target.setReferenceTaxon(null);
+ target.setTaxonGroup(null);
+
+ // Sorting measurement
+ if (copyIfNull && (sortingPmfmId == null || sortingQualitativeValueId == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (sortingPmfmId != null && sortingQualitativeValueId != null) {
+ SortingMeasurement sm = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId);
+ notChangedSortingMeasurements.remove(sm);
+ }
+
+ // Sampling Ratio
+ if (copyIfNull && (sampleWeight == null || weight == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (sampleWeight != null && weight != null) {
+ String samplingRatioText = weight + "/" + sampleWeight;
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(weight / sampleWeight);
+ }
+
+ // Weight
+ if (copyIfNull && (sampleWeight == null && weight == null)) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (sampleWeight != null || weight != null) {
+ Float batchReferenceWeight = weight;
+ if (batchReferenceWeight == null) {
+ batchReferenceWeight = sampleWeight;
+ }
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected void beanToEntityReferenceTaxonBatch(
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
+ fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
+ fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
+ Integer recorderDepartmentId,
+ Integer referenceTaxonId,
+ Float weight,
+ Float sampleWeight,
+ boolean copyIfNull) {
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // Some mandatory properties :
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRootBatch(rootBatch);
+ target.setParentBatch(parentBatch);
+ target.setExhaustiveInventory(true);
+
+ // Reference taxon
+ target.setReferenceTaxon(load(ReferenceTaxonImpl.class, referenceTaxonId));
+ target.setTaxonGroup(null);
+
+ // Sampling Ratio
+ if (copyIfNull && (sampleWeight == null || weight == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (sampleWeight != null && weight != null) {
+ String samplingRatioText = weight + "/" + sampleWeight;
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(weight / sampleWeight);
+ }
+
+ // Weight
+ if (copyIfNull && (sampleWeight == null && weight == null)) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (sampleWeight != null || weight != null) {
+ Float batchReferenceWeight = weight;
+ if (batchReferenceWeight == null) {
+ batchReferenceWeight = sampleWeight;
+ }
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected Integer getRecorderDepartmentId() {
+ // TODO BL : voir si on peut récupérer le departement (du 1er saisisseur ?)
+ return enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
+ }
+}
\ No newline at end of file
Property changes on: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -27,6 +27,7 @@
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
+import fr.ifremer.tutti.persistence.ProgressionModel;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
@@ -83,26 +84,32 @@
* @param localProperties properties to connect to local database
* @param remoteProperties properties to connect to remove database
* @param dialect dialect used to seek metadata of databases.
- * @return Result of the synchronize operation, if there is an error then
- * the {@link ReferentialSynchronizeResult#isSuccess()} is {@code false}
- * and you can get the error at
- * {@link ReferentialSynchronizeResult#getError()}
+ * @param result Result of the synchronize operation, if there is an error then
+ * the {@link ReferentialSynchronizeResult#isSuccess()} is {@code false}
+ * and you can get the error at
+ * {@link ReferentialSynchronizeResult#getError()}
*/
- public ReferentialSynchronizeResult synchronize(Properties localProperties,
- Properties remoteProperties,
- Dialect dialect) {
+ public void prepare(Properties localProperties,
+ Properties remoteProperties,
+ Dialect dialect,
+ ReferentialSynchronizeResult result) {
- ReferentialSynchronizeResult result = new ReferentialSynchronizeResult(
- TuttiEntities.getUrl(localProperties),
- TuttiEntities.getUrl(remoteProperties));
+ result.setLocalUrl(TuttiEntities.getUrl(localProperties));
+ result.setRemoteUrl(TuttiEntities.getUrl(remoteProperties));
+
Connection localConnection = null;
Connection remoteConnection = null;
try {
+ ProgressionModel progressionModel = result.getProgressionModel();
+ progressionModel.setMessage("Connection à la base de synchronisation");
+
// create local connection
localConnection = TuttiEntities.createConnection(localProperties);
+ progressionModel.setMessage("Connection à la base à synchroniser");
+
// create remote Connection
remoteConnection = TuttiEntities.createConnection(remoteProperties);
@@ -112,6 +119,8 @@
TuttiDatabaseMetadata remoteMeta =
loadDatabaseMetadata(remoteConnection, dialect);
+ progressionModel.setMessage("Vérification de la compatibilité des schémas");
+
// check schema
try {
checkSchemas(localMeta, remoteMeta);
@@ -127,6 +136,8 @@
String tableName = tuttiTable.name();
+ progressionModel.setMessage("Lecture de la table " + tableName);
+
TuttiTableMetadata table = remoteMeta.getTable(tableName);
if (log.isDebugEnabled()) {
@@ -142,40 +153,100 @@
if (log.isInfoEnabled()) {
log.info("Total rows to update: " + totalRows);
}
+ localConnection.rollback();
+ }
+ } catch (SQLException e) {
+ try {
+ if (localConnection != null) {
+ localConnection.rollback();
+ }
+ } catch (SQLException e1) {
- // prepare target (desactivate constraints)
- prepareSynch(localConnection);
+ // ignore the rolback error
+ }
+ result.setError(e);
+ } finally {
+ JdbcUtils.closeConnection(remoteConnection);
+ JdbcUtils.closeConnection(localConnection);
+ }
+ }
- try {
- for (TuttiTable tuttiTable : TuttiTable.values()) {
+ /**
+ * Synchronize database given from {@code localProperties} (means the
+ * database to update) with remote database (means the database which
+ * contains the referential to use) given by {@code remoteProperties}
+ * using the given {@code dialect} to inspect databases metadatas.
+ *
+ * @param localProperties properties to connect to local database
+ * @param remoteProperties properties to connect to remove database
+ * @param dialect dialect used to seek metadata of databases.
+ * @return Result of the synchronize operation, if there is an error then
+ * the {@link ReferentialSynchronizeResult#isSuccess()} is {@code false}
+ * and you can get the error at
+ * {@link ReferentialSynchronizeResult#getError()}
+ */
+ public ReferentialSynchronizeResult synchronize(Properties localProperties,
+ Properties remoteProperties,
+ Dialect dialect,
+ ReferentialSynchronizeResult result) {
- String tableName = tuttiTable.name();
- TuttiTableMetadata table = remoteMeta.getTable(tableName);
+ Connection localConnection = null;
+ Connection remoteConnection = null;
+ try {
- if (log.isInfoEnabled()) {
- log.info("Synchronize table: " + tableName);
- }
- synchronizeTable(table,
- localConnection,
- remoteConnection,
- result);
- }
+ // create local connection
+ localConnection = TuttiEntities.createConnection(localProperties);
+
+ // create remote Connection
+ remoteConnection = TuttiEntities.createConnection(remoteProperties);
+
+ // load metas
+ TuttiDatabaseMetadata remoteMeta =
+ loadDatabaseMetadata(remoteConnection, dialect);
+
+ // set total in progression model
+ ProgressionModel progressionModel = result.getProgressionModel();
+ progressionModel.setTotal(result.getTotalRows());
+
+ // prepare target (desactivate constraints)
+ prepareSynch(localConnection);
+
+ try {
+
+ for (TuttiTable tuttiTable : TuttiTable.values()) {
+
+ String tableName = tuttiTable.name();
+
+ progressionModel.setMessage("Mise à jour de la table " + tableName);
+
+ TuttiTableMetadata table = remoteMeta.getTable(tableName);
+
if (log.isInfoEnabled()) {
- long totalInserts = result.getTotalInserts();
- long totalUpdates = result.getTotalUpdates();
- log.info("Total rows to treat: " + totalRows);
- log.info("Total rows inserted: " + totalInserts);
- log.info("Total rows updated: " + totalUpdates);
- log.info("Total rows treated: " + (totalInserts + totalUpdates));
+ log.info("Synchronize table: " + tableName);
}
- } finally {
- releaseSynch(localConnection);
+ synchronizeTable(table,
+ localConnection,
+ remoteConnection,
+ result);
}
+ if (log.isInfoEnabled()) {
+ long totalInserts = result.getTotalInserts();
+ long totalUpdates = result.getTotalUpdates();
+ log.info("Total rows to treat: " + result.getTotalRows());
+ log.info("Total rows inserted: " + totalInserts);
+ log.info("Total rows updated: " + totalUpdates);
+ log.info("Total rows treated: " + (totalInserts + totalUpdates));
+ }
+ } finally {
+ releaseSynch(localConnection);
+ }
- localConnection.commit();
- }
+ progressionModel.setMessage("Sauvegarde des données dans la base locale");
+
+ localConnection.commit();
+
} catch (SQLException e) {
try {
if (localConnection != null) {
@@ -446,6 +517,10 @@
countR++;
+ if (countR % 1000 == 0) {
+ result.getProgressionModel().increments(1000);
+ }
+
if (insertCount > 0 && insertCount % 1000 == 0) {
insertStatement.executeBatch();
insertStatement.clearBatch();
@@ -480,6 +555,8 @@
log.debug(String.format("%s INSERT count: %s", tablePrefix, result.getNbInserts(tableName)));
log.debug(String.format("%s UPDATE count: %s", tablePrefix, result.getNbUpdates(tableName)));
}
+
+ result.getProgressionModel().increments(countR % 1000);
}
protected String getTablePrefix(TuttiTableMetadata table) {
@@ -494,6 +571,8 @@
String tableName = table.getName();
+ result.getProgressionModel().setMessage("Mise à jour de la table " + tableName);
+
String tablePrefix = getTablePrefix(table);
// get last updateDate used by local db
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -27,6 +27,7 @@
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+import fr.ifremer.tutti.persistence.ProgressionModel;
import java.sql.Timestamp;
import java.util.Map;
@@ -77,15 +78,28 @@
*/
protected final Set<String> tableNames = Sets.newHashSet();
- protected final String localUrl;
+ protected String localUrl;
- protected final String remoteUrl;
+ protected String remoteUrl;
+ protected final ProgressionModel progressionModel = new ProgressionModel();
+
+ public ReferentialSynchronizeResult() {
+ }
+
public ReferentialSynchronizeResult(String localUrl, String remoteUrl) {
this.localUrl = localUrl;
this.remoteUrl = remoteUrl;
}
+ public void setLocalUrl(String localUrl) {
+ this.localUrl = localUrl;
+ }
+
+ public void setRemoteUrl(String remoteUrl) {
+ this.remoteUrl = remoteUrl;
+ }
+
public boolean isSuccess() {
return error == null;
}
@@ -98,28 +112,32 @@
this.error = error;
}
+ public ProgressionModel getProgressionModel() {
+ return progressionModel;
+ }
+
public Set<String> getTableNames() {
return ImmutableSet.copyOf(tableNames);
}
- public long getTotalRows() {
- long result = 0;
+ public int getTotalRows() {
+ int result = 0;
for (Integer nb : rowHits.values()) {
result += nb;
}
return result;
}
- public long getTotalInserts() {
- long result = 0;
+ public int getTotalInserts() {
+ int result = 0;
for (Integer nb : insertHits.values()) {
result += nb;
}
return result;
}
- public long getTotalUpdates() {
- long result = 0;
+ public int getTotalUpdates() {
+ int result = 0;
for (Integer nb : updateHits.values()) {
result += nb;
}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeService.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeService.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -55,13 +55,27 @@
Dialect getLocalDialect();
/**
+ * Prepare the synchronize operation from the local data database supported
+ * by this service, says just compute nb rows to update for each table and
+ * update the result model.
+ *
+ * @param remoteConnectionProperties connection properties of the remote
+ * database used to synchronize referential
+ * @param result result of the operation
+ * @see ReferentialSynchronizeResult
+ */
+ void prepare(Properties remoteConnectionProperties,
+ ReferentialSynchronizeResult result);
+
+ /**
* Launch the synchronize operation from the local data database supported
* by this service.
*
* @param remoteConnectionProperties connection properties of the remote
* database used to synchronize referential
- * @return result of the operation
+ * @param result model
* @see ReferentialSynchronizeResult
*/
- ReferentialSynchronizeResult synchronize(Properties remoteConnectionProperties);
+ void synchronize(Properties remoteConnectionProperties,
+ ReferentialSynchronizeResult result);
}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImpl.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -24,6 +24,7 @@
* #L%
*/
+import com.google.common.base.Preconditions;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import fr.ifremer.tutti.persistence.service.AbstractPersistenceService;
import org.apache.commons.dbcp.BasicDataSource;
@@ -75,10 +76,26 @@
}
@Override
- public ReferentialSynchronizeResult synchronize(Properties remoteConnectionProperties) {
+ public void prepare(Properties remoteConnectionProperties, ReferentialSynchronizeResult result) {
+ Preconditions.checkNotNull(result);
+ Preconditions.checkNotNull(remoteConnectionProperties);
+ helper.prepare(getLocalConnectionProperties(),
+ remoteConnectionProperties,
+ getLocalDialect(),
+ result);
+ }
+
+ @Override
+ public void synchronize(Properties remoteConnectionProperties, ReferentialSynchronizeResult result) {
//TODO Evict all caches, restart application (but not from here,...)
- return helper.synchronize(getLocalConnectionProperties(),
- remoteConnectionProperties,
- getLocalDialect());
+
+ Preconditions.checkNotNull(result);
+ Preconditions.checkNotNull(remoteConnectionProperties);
+ Preconditions.checkState(result.isSuccess());
+
+ helper.synchronize(getLocalConnectionProperties(),
+ remoteConnectionProperties,
+ getLocalDialect(),
+ result);
}
}
Modified: trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties
===================================================================
--- trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties 2013-02-14 23:53:34 UTC (rev 414)
@@ -380,5 +380,5 @@
#Reference taxon correspondant à "Biota" (ou "Vie")
ReferenceTaxonId.LIFE=7637
#Reference taxon correspondant à "Non Biota" (ou "Non Vie" - matière inerte)
-# TODO : a creer dans la base harmonie et a�changer !
+# TODO : a creer dans la base harmonie et achanger !
ReferenceTaxonId.INERT=1
\ No newline at end of file
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/DatabaseResource.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -270,7 +270,7 @@
if (p != null) {
TuttiEntities.fillConnectionProperties(
p,
- "jdbc:hsqldb:file:" + target.getAbsolutePath() + "/" + config.getDbName(),
+ TuttiEntities.getJdbcUrl(target, config.getDbName()),
config.getJdbcUsername(),
config.getJdbcPassword());
}
@@ -377,7 +377,7 @@
log.info("Create new db at " + directory);
}
addToDestroy(directory);
- String jdbcUrl = "jdbc:hsqldb:file:" + directory.getAbsolutePath() + "/" + dbName;
+ String jdbcUrl = TuttiEntities.getJdbcUrl(directory, dbName);
String user = "SA";
String password = "";
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -1,187 +1,187 @@
-package fr.ifremer.tutti.persistence.service;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id: CatchBatchPersistenceServiceReadTest.java 379 2013-02-10 13:41:29Z tchemit $
- * $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/test/j… $
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.List;
-import java.util.Map;
-
-import fr.ifremer.tutti.persistence.DatabaseResource;
-import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
-import fr.ifremer.tutti.persistence.entities.data.Cruise;
-import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
-import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
-
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.springframework.dao.DataRetrievalFailureException;
-
-import com.google.common.collect.Maps;
-
-/**
- * To test {@link CatchBatchPersistenceService} for read operation.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.0
- */
-public class BatchPersistenceServiceReadTest {
-
- @ClassRule
- public static final DatabaseResource dbResource = DatabaseResource.readDb();
-
- protected BatchPersistenceService service;
- protected FishingOperationPersistenceService fishingOperationService;
- protected FishingOperation fishingOperation;
-
- @Before
- public void setUp() throws Exception {
- service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
- fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
-
- List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
- assertNotNull(fishingOperations);
- assertTrue(fishingOperations.size() > 0);
- fishingOperation = fishingOperations.get(0);
- assertNotNull(fishingOperation);
- assertNotNull(fishingOperation.getId());
- }
-
- @Test
- public void getCatchBatchFromFishingOperation() throws Exception {
-
- try {
- CatchBatch catchBatch = service.getCatchBatchFromFishingOperation(fishingOperation.getId());
- fail("batch tree must be invalid (old CGFS tree structure), for fishing operation id=" + fishingOperation.getId());
- }
- catch(DataRetrievalFailureException drfe) {
- // success
- }
- }
-
- @Test
- public void getAllRootSpeciesBatch(/*String fishingOperationId*/) {
- }
-
- @Test
- public void getAllSpeciesBatchFrequency(/*String speciesBatchId*/) {
-
- }
-
- public static void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
- assertNotNull(actualBatch);
- assertNotNull(actualBatch.getId());
- if (assertIdEquals && expectedBatch.getId() != null) {
- assertEquals(expectedBatch.getId(), actualBatch.getId());
- }
- assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
- assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
- if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
- assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
- actualBatch.getSampleCategoryValue());
- assertEquals(
- ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
- ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
- } else {
- assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
- }
- assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
- assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
- assertEquals(expectedBatch.getComment(), actualBatch.getComment());
-
- // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
- // (Because getSpeciesBatch(id) could not always retrieve the species)
- if (expectedBatch.getSpecies() != null && (
- expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
- || actualBatch.getSpecies() != null)) {
- assertNotNull(actualBatch.getSpecies());
- assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
- }
- }
-
- public static void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
- assertNotNull(actualFrequencies);
- assertEquals(expectedFrequencies.size(), actualFrequencies.size());
-
- // Store actual batches into a map, using the length as key
- Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
- for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
- expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
- }
-
- // Store expected batches into a map, using the length as key
- Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
- for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
- assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
- actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
- assertNotNull(speciesBatchFrequency.getId());
- }
-
- for (Float lengthStep : expectedLengthMap.keySet()) {
- SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
- SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
- if (assertIdEquals) {
- assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
- }
- assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
- assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
- assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
- assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
- assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
- //assertNotNull(expectedBatchFrequency.getBatch());
- //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
- }
- }
-
- public static SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
- return getSpeciesBatch(speciesBatchId, TuttiPersistenceServiceLocator.getBatchPersistenceService().getAllRootSpeciesBatch(fishingOperationId));
- }
-
- public static SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
- if (speciesBatchs == null) {
- return null;
- }
- for (SpeciesBatch speciesBatch : speciesBatchs) {
- if (speciesBatchId.equals(speciesBatch.getId())) {
- return speciesBatch;
- }
- if (speciesBatch.getChildBatchs() != null) {
- speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
- if (speciesBatch != null) {
- return speciesBatch;
- }
- }
- }
- return null;
- }
-
-}
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.Cruise;
+import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.springframework.dao.DataRetrievalFailureException;
+
+import com.google.common.collect.Maps;
+
+/**
+ * To test {@link CatchBatchPersistenceService} for read operation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class BatchPersistenceServiceReadTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.readDb();
+
+ protected BatchPersistenceService service;
+ protected FishingOperationPersistenceService fishingOperationService;
+ protected FishingOperation fishingOperation;
+
+ @Before
+ public void setUp() throws Exception {
+ service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
+ fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
+
+ List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
+ assertNotNull(fishingOperations);
+ assertTrue(fishingOperations.size() > 0);
+ fishingOperation = fishingOperations.get(0);
+ assertNotNull(fishingOperation);
+ assertNotNull(fishingOperation.getId());
+ }
+
+ @Test
+ public void getCatchBatchFromFishingOperation() throws Exception {
+
+ try {
+ CatchBatch catchBatch = service.getCatchBatchFromFishingOperation(fishingOperation.getId());
+ fail("batch tree must be invalid (old CGFS tree structure), for fishing operation id=" + fishingOperation.getId());
+ }
+ catch(DataRetrievalFailureException drfe) {
+ // success
+ }
+ }
+
+ @Test
+ public void getAllRootSpeciesBatch(/*String fishingOperationId*/) {
+ }
+
+ @Test
+ public void getAllSpeciesBatchFrequency(/*String speciesBatchId*/) {
+
+ }
+
+ public static void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
+ assertNotNull(actualBatch);
+ assertNotNull(actualBatch.getId());
+ if (assertIdEquals && expectedBatch.getId() != null) {
+ assertEquals(expectedBatch.getId(), actualBatch.getId());
+ }
+ assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
+ assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
+ if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
+ assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
+ actualBatch.getSampleCategoryValue());
+ assertEquals(
+ ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
+ ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
+ } else {
+ assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
+ }
+ assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
+ assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
+ assertEquals(expectedBatch.getComment(), actualBatch.getComment());
+
+ // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
+ // (Because getSpeciesBatch(id) could not always retrieve the species)
+ if (expectedBatch.getSpecies() != null && (
+ expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
+ || actualBatch.getSpecies() != null)) {
+ assertNotNull(actualBatch.getSpecies());
+ assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
+ }
+ }
+
+ public static void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
+ assertNotNull(actualFrequencies);
+ assertEquals(expectedFrequencies.size(), actualFrequencies.size());
+
+ // Store actual batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
+ expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ }
+
+ // Store expected batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
+ assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
+ actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ assertNotNull(speciesBatchFrequency.getId());
+ }
+
+ for (Float lengthStep : expectedLengthMap.keySet()) {
+ SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
+ SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
+ if (assertIdEquals) {
+ assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
+ }
+ assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
+ assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
+ assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
+ assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
+ assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
+ //assertNotNull(expectedBatchFrequency.getBatch());
+ //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
+ }
+ }
+
+ public static SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
+ return getSpeciesBatch(speciesBatchId, TuttiPersistenceServiceLocator.getBatchPersistenceService().getAllRootSpeciesBatch(fishingOperationId));
+ }
+
+ public static SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
+ if (speciesBatchs == null) {
+ return null;
+ }
+ for (SpeciesBatch speciesBatch : speciesBatchs) {
+ if (speciesBatchId.equals(speciesBatch.getId())) {
+ return speciesBatch;
+ }
+ if (speciesBatch.getChildBatchs() != null) {
+ speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
+ if (speciesBatch != null) {
+ return speciesBatch;
+ }
+ }
+ }
+ return null;
+ }
+
+}
Property changes on: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -1,621 +1,621 @@
-package fr.ifremer.tutti.persistence.service;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id: CatchBatchPersistenceServiceWriteTest.java 379 2013-02-10 13:41:29Z tchemit $
- * $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/test/j… $
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import fr.ifremer.tutti.persistence.DatabaseResource;
-import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
-import fr.ifremer.tutti.persistence.entities.data.Cruise;
-import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
-import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
-import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
-import fr.ifremer.tutti.persistence.entities.referential.Species;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.springframework.dao.DataRetrievalFailureException;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.List;
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.*;
-
-/**
- * To test {@link CatchBatchPersistenceService} for write operation.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.0
- */
-public class BatchPersistenceServiceWriteTest {
-
- @ClassRule
- public static final DatabaseResource dbResource = DatabaseResource.writeDb();
-
- protected BatchPersistenceService service;
-
- protected CruisePersistenceService cruiseService;
-
- protected FishingOperationPersistenceService fishingOperationService;
-
- protected CatchBatchPersistenceService catchBatchService;
-
- protected ReferentialPersistenceService referentialService;
-
- protected Cruise cruise;
-
- protected FishingOperation fishingOperationNoCatchBatch;
-
- protected FishingOperation fishingOperationWithEmptyBatch;
-
- protected CatchBatch catchBacth;
-
- protected List<Species> species;
-
- protected Caracteristic sortedUnsortedPMFM;
-
- protected CaracteristicQualitativeValue horsVracQualitativeValue;
-
- protected CaracteristicQualitativeValue vracQualitativeValue;
-
- protected Caracteristic maturityPMFM;
-
- protected CaracteristicQualitativeValue firstMaturityQualitativeValue;
-
- protected Caracteristic sexPMFM;
-
- protected CaracteristicQualitativeValue maleQualitativeValue;
-
- protected CaracteristicQualitativeValue femaleQualitativeValue;
-
- protected CaracteristicQualitativeValue unkQualitativeValue;
-
- protected Caracteristic frequencyPMFM;
-
- @Before
- public void setUp() throws Exception {
- service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
- cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService();
- fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
- catchBatchService = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService();
- referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService();
-
- species = referentialService.getAllSpecies();
- assertNotNull(species);
- assertTrue(species.size() > 2);
-
- cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId());
- cruise.setId(null);
- Calendar calendar = new GregorianCalendar();
- cruise.setBeginDate(calendar.getTime());
- cruise.setYear(calendar.get(Calendar.YEAR));
- calendar.add(Calendar.MONTH, 1); // add one month
- cruise.setEndDate(calendar.getTime());
- cruise = cruiseService.createCruise(cruise);
-
- // Create a first operation, with no cacth batch : to test CatchBatch insert/update :
- List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
- assertNotNull(fishingOperations);
- assertTrue(fishingOperations.size() > 0);
- fishingOperationNoCatchBatch = fishingOperations.get(0);
- fishingOperationNoCatchBatch = fishingOperationService.getFishingOperation(fishingOperationNoCatchBatch.getId());
- fishingOperationNoCatchBatch.setId(null);
- fishingOperationNoCatchBatch.setCruise(cruise);
- calendar.setTime(new Date());
- calendar.set(Calendar.HOUR_OF_DAY, 1);
- calendar.set(Calendar.MILLISECOND, 0);
- fishingOperationNoCatchBatch.setGearShootingStartDate(calendar.getTime());
- calendar.setTime(new Date());
- calendar.set(Calendar.HOUR_OF_DAY, 10);
- calendar.set(Calendar.MILLISECOND, 0);
- fishingOperationNoCatchBatch.setGearShootingEndDate(calendar.getTime());
- fishingOperationNoCatchBatch = fishingOperationService.createFishingOperation(fishingOperationNoCatchBatch);
-
- // Create a second operation, with no cacth batch : to test CatchBatch insert/update :
- fishingOperationWithEmptyBatch = fishingOperations.get(1);
- fishingOperationWithEmptyBatch = fishingOperationService.getFishingOperation(fishingOperationWithEmptyBatch.getId());
- fishingOperationWithEmptyBatch.setId(null);
- fishingOperationWithEmptyBatch.setCruise(cruise);
- calendar.setTime(new Date());
- calendar.set(Calendar.HOUR_OF_DAY, 11);
- calendar.set(Calendar.MILLISECOND, 0);
- fishingOperationWithEmptyBatch.setGearShootingStartDate(calendar.getTime());
- calendar.setTime(new Date());
- calendar.set(Calendar.HOUR_OF_DAY, 12);
- calendar.set(Calendar.MILLISECOND, 0);
- fishingOperationWithEmptyBatch.setGearShootingEndDate(calendar.getTime());
- fishingOperationWithEmptyBatch = fishingOperationService.createFishingOperation(fishingOperationWithEmptyBatch);
-
- catchBacth = new CatchBatch();
- catchBacth.setFishingOperation(fishingOperationWithEmptyBatch);
- catchBacth = catchBatchService.createCatchBatch(catchBacth);
-
- sortedUnsortedPMFM = referentialService.getSortedUnsortedCaracteristic();
- horsVracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(0);
- vracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(1);
- maturityPMFM = referentialService.getMaturityCaracteristic();
- firstMaturityQualitativeValue = maturityPMFM.getQualitativeValue(0);
- sexPMFM = referentialService.getSexCaracteristic();
- maleQualitativeValue = sexPMFM.getQualitativeValue(1);
- femaleQualitativeValue = sexPMFM.getQualitativeValue(2);
- unkQualitativeValue = sexPMFM.getQualitativeValue(3);
-
- List<Caracteristic> cara = referentialService.getAllCaracteristic();
- for (Caracteristic caracteristic : cara) {
- if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER
- && caracteristic.getPrecision() != null
- && caracteristic.getPrecision() == 0.5f) {
- frequencyPMFM = caracteristic;
- break;
- }
- }
- assertNotNull("no numerical PMFM with a precision has been found. Could not define a PMFM for batch frequencies.", frequencyPMFM);
-
- }
-
- @Test
- public void createAndSaveCatchBatch() throws Exception {
- CatchBatch catchBatch;
-
- catchBatch = new CatchBatch();
- catchBatch.setFishingOperation(fishingOperationNoCatchBatch);
-
- // -----------------------------------------------------------------------------
- // 1. Test with only mandatory properties
- // -----------------------------------------------------------------------------
-
- // Create and reload (test round trip)
- assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
-
- // -----------------------------------------------------------------------------
- // 2. Test with all properties
- // -----------------------------------------------------------------------------
- catchBatch.setId(null);
- // total weight : 100kg
- catchBatch.setCatchTotalWeight(75f);
- // Vrac :
- {
- // note : poids trie par la balance tremis (thalassa) (init par pupitri)
- catchBatch.setCatchTotalSortedTremisWeight(50f);
- // note : poids vrac caroussel (thalassa) (init par pupitri) (vrac trie) ou bien "poids trié fournie par la table de tri (Sum(Si)
- catchBatch.setCatchTotalSortedCarousselWeight(45f);
-
- // Species
- {
- catchBatch.setSpeciesTotalSortedWeight(12f);
- catchBatch.setSpeciesTotalSampleSortedWeight(8f);
- catchBatch.setSpeciesTotalLivingNotItemizedWeight(0.2f);
- catchBatch.setSpeciesTotalInertWeight(0.1f);
- }
- }
- // Hors Vrac : 10kg
- {
- catchBatch.setCatchTotalUnsortedWeight(10f);
-
- // Species
- {
- catchBatch.setSpeciesTotalUnsortedWeight(10f);
- }
- }
- // Rejet : 15kg
- catchBatch.setCatchTotalRejectedWeight(15f);
-
- // Create and reload (test round trip)
- assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
-
- // -----------------------------------------------------------------------------
- // 2. Test save after modification
- // -----------------------------------------------------------------------------
- catchBatch.setCatchTotalSortedTremisWeight(null);
- catchBatch.setCatchTotalSortedCarousselWeight(null);
- catchBatch.setSpeciesTotalSortedWeight(null);
- catchBatch.setSpeciesTotalSampleSortedWeight(null);
- catchBatch.setCatchTotalUnsortedWeight(null);
- catchBatch.setSpeciesTotalUnsortedWeight(null);
-
- assertSaveAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
- }
-
- @Test
- public void createAndSaveSpeciesBatchAndFrequencies() {
- SpeciesBatch esp1Batch = null;
- SpeciesBatch esp2Batch = null;
- SpeciesBatch frequenciesParentBatch = null;
- SpeciesBatch batch = null;
- Species taxon1 = species.get(0);
- Species taxon2 = species.get(1);
-
- // -----------------------------------------------------------------------------
- // 1. Test with only mandatory properties
- // -----------------------------------------------------------------------------
- // batch : "ESP1 - Vrac/5"
- batch = new SpeciesBatch();
- batch.setParentBatch(null);
- batch.setFishingOperation(fishingOperationNoCatchBatch);
- batch.setSpecies(taxon1);
- batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
- batch.setSampleCategoryValue(vracQualitativeValue);
- batch.setSampleCategoryWeight(5f);
-
- assertCreateAndReloadSpeciesBatch(batch, null);
-
- // Save ESP1 batch
- esp1Batch = batch;
-
- // -----------------------------------------------------------------------------
- // 2. Test child "Male/2"
- // -----------------------------------------------------------------------------
- // Batch : ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7
- batch = new SpeciesBatch();
- batch.setId(null);
- batch.setParentBatch(esp1Batch);
- batch.setSpecies(taxon1);
- batch.setComment("ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7");
- batch.setSampleCategoryType(SampleCategoryEnum.sex);
- batch.setSampleCategoryValue(maleQualitativeValue);
- batch.setSampleCategoryWeight(2f);
- batch.setWeight(1f);
- batch.setNumber(7);
-
- assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
-
- // -----------------------------------------------------------------------------
- // 3. Test child "Female/2"
- // -----------------------------------------------------------------------------
- // Batch : ESP1 - Vrac/5 Female/3 Nombre/14
- batch = new SpeciesBatch();
- batch.setId(null);
- batch.setParentBatch(esp1Batch);
- batch.setSpecies(taxon1);
- batch.setComment("ESP1 - Vrac/5 Female/3 Nombre/14");
- batch.setSampleCategoryType(SampleCategoryEnum.sex);
- batch.setSampleCategoryValue(femaleQualitativeValue);
- batch.setSampleCategoryWeight(3f);
- batch.setWeight(null);
- batch.setNumber(14);
-
- assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
-
- // -----------------------------------------------------------------------------
- // 4. Test : ESP2 - Vrac/7
- // \- ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
- // -----------------------------------------------------------------------------
- // batch : "ESP2 - Vrac/7 "
- batch = new SpeciesBatch();
- batch.setParentBatch(null);
- batch.setSpecies(taxon2);
- batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
- batch.setSampleCategoryValue(vracQualitativeValue);
- batch.setSampleCategoryWeight(7f);
-
- assertCreateAndReloadSpeciesBatch(batch, null);
- esp2Batch = batch;
-
- // Batch : ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
- batch = new SpeciesBatch();
- batch.setId(null);
- batch.setParentBatch(esp2Batch);
- batch.setSpecies(taxon2);
- batch.setComment("ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11");
- batch.setSampleCategoryType(SampleCategoryEnum.maturity);
- batch.setSampleCategoryValue(firstMaturityQualitativeValue);
- batch.setSampleCategoryWeight(2f);
- batch.setWeight(1f);
- batch.setNumber(11);
-
- assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
-
- // -----------------------------------------------------------------------------
- // 5. Test save after modifications
- // -----------------------------------------------------------------------------
- // Batch : ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99
- batch.setComment("ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99");
- batch.setSampleCategoryType(SampleCategoryEnum.sex);
- batch.setSampleCategoryValue(unkQualitativeValue);
- batch.setSampleCategoryWeight(1.75f);
- batch.setWeight(1.11f);
- batch.setFishingOperation(fishingOperationWithEmptyBatch);
- batch.setNumber(99);
-
- // Save and reload, then check
- SpeciesBatch savedBatch = service.saveSpeciesBatch(batch);
- assertSpeciesBatch(savedBatch, batch, false);
- SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), savedBatch.getId());
- assertSpeciesBatch(savedBatch, reloadedBatch, true);
-
- // Save batch for later
- frequenciesParentBatch = batch;
-
- // -----------------------------------------------------------------------------
- // 6. Test change species
- // -----------------------------------------------------------------------------
- esp2Batch.setSpecies(taxon1);
- service.changeSpeciesBatchSpecies(esp2Batch.getId(), taxon1);
- assertSpeciesBatch(savedBatch, batch, false);
- reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp2Batch.getId());
- assertSpeciesBatch(esp2Batch, reloadedBatch, true);
-
- // -----------------------------------------------------------------------------
- // 7. Test get all root species
- // -----------------------------------------------------------------------------
- List<SpeciesBatch> rootSpeciesBatch = service.getAllRootSpeciesBatch(fishingOperationWithEmptyBatch.getId());
- assertNotNull(rootSpeciesBatch);
- assertEquals(2, rootSpeciesBatch.size());
- assertNotNull(rootSpeciesBatch.get(0).getChildBatchs());
- assertTrue(rootSpeciesBatch.get(0).getChildBatchs().size() > 0);
- assertNotNull(rootSpeciesBatch.get(1).getChildBatchs());
- assertTrue(rootSpeciesBatch.get(1).getChildBatchs().size() > 0);
-
- // -----------------------------------------------------------------------------
- // 8. Test batch frequency creation
- // -----------------------------------------------------------------------------
-
- List<SpeciesBatchFrequency> frequencies = Lists.newArrayList();
- float lengthStep = 0.5f;
- for (float length = lengthStep; length < lengthStep * 20; length += lengthStep) {
- SpeciesBatchFrequency frequency = new SpeciesBatchFrequency();
- frequency.setLengthStep(length);
- frequency.setNumber((int) (length * 2));
- frequency.setWeight(0.01f * length * 2);
- frequency.setLengthStepCaracteristic(frequencyPMFM);
- frequency.setBatch(frequenciesParentBatch);
- frequency.setComment("comments");
- frequencies.add(frequency);
- }
- List<SpeciesBatchFrequency> createdFrequencies = assertCreateAndReloadSpeciesBatchFrequency(frequencies, frequenciesParentBatch.getId());
-
- // -----------------------------------------------------------------------------
- // 9. Test batch frequency update
- // -----------------------------------------------------------------------------
- // Update some batchs (1cm, 2cm, etc)
- for (SpeciesBatchFrequency speciesBatchFrequency : createdFrequencies) {
- float length = speciesBatchFrequency.getLengthStep();
- if ((float) (int) length == length) {
- speciesBatchFrequency.setNumber(12);
- speciesBatchFrequency.setComment(null);
- }
- }
- // And remove the last item (should be deleted in DB)
- createdFrequencies.remove(createdFrequencies.size()-1);
- List<SpeciesBatchFrequency> savedFrequencies = service.saveSpeciesBatchFrequency(frequenciesParentBatch.getId(), frequencies);
- assertBatchFrequencies(createdFrequencies, savedFrequencies, true);
- }
-
- @Test
- public void deleteSpeciesBatch(/*String id*/) {
- SpeciesBatch esp1Batch;
- SpeciesBatch batch;
- Species taxon1 = species.get(0);
-
- // -----------------------------------------------------------------------------
- // 1. Create two batchs (parent + child), then remove the parent batch
- // -----------------------------------------------------------------------------
- // batch : ESP1 Vrac/5
- batch = new SpeciesBatch();
- batch.setParentBatch(null);
- batch.setFishingOperation(fishingOperationWithEmptyBatch);
- batch.setSpecies(taxon1);
- batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
- batch.setSampleCategoryValue(vracQualitativeValue);
- batch.setSampleCategoryWeight(5f);
- assertCreateAndReloadSpeciesBatch(batch, null);
- esp1Batch = batch;
-
- // batch : ESP1 Vrac/5 Male/2
- batch = new SpeciesBatch();
- batch.setParentBatch(esp1Batch);
- batch.setFishingOperation(fishingOperationWithEmptyBatch);
- batch.setSpecies(taxon1);
- batch.setSampleCategoryType(SampleCategoryEnum.sex);
- batch.setSampleCategoryValue(maleQualitativeValue);
- batch.setSampleCategoryWeight(2f);
- assertCreateAndReloadSpeciesBatch(batch, esp1Batch.getId());
-
- // Try to remove
- service.deleteSpeciesBatch(esp1Batch.getId());
-
- // Check if remove
- try {
- batch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp1Batch.getId());
- assertNull(batch);
- } catch (DataRetrievalFailureException drfe) {
- assertNotNull(drfe);
- }
- }
-
- protected void assertCreateAndReloadSpeciesBatch(SpeciesBatch batch, String parentBatchId) {
- batch.setFishingOperation(fishingOperationWithEmptyBatch);
-
- // Create batch
- SpeciesBatch createdBatch = service.createSpeciesBatch(batch, parentBatchId);
- assertSpeciesBatch(batch, createdBatch, false);
-
- // then reload (for round trip check)
- SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), createdBatch.getId());
- if (parentBatchId == null) {
- assertNull(reloadedBatch.getParentBatch());
- } else {
- assertNotNull(reloadedBatch.getParentBatch());
- assertEquals(parentBatchId, reloadedBatch.getParentBatch().getId());
- }
- assertSpeciesBatch(createdBatch, reloadedBatch, false);
-
- batch.setId(createdBatch.getId());
- }
-
- protected void assertCreateAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
- CatchBatch createdCatchBatch = service.createCatchBatch(catchBatch);
- assertNotNull(createdCatchBatch);
- assertNotNull(createdCatchBatch.getId());
- assertCatchBatch(catchBatch, createdCatchBatch, false);
-
- CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
- assertCatchBatch(createdCatchBatch, reloadedCatchBatch, true);
-
- catchBatch.setId(createdCatchBatch.getId());
- }
-
- protected void assertSaveAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
- CatchBatch savedCatchBatch = service.saveCatchBatch(catchBatch);
- assertNotNull(savedCatchBatch);
- assertNotNull(savedCatchBatch.getId());
- assertCatchBatch(catchBatch, savedCatchBatch, false);
-
- CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
- assertCatchBatch(savedCatchBatch, reloadedCatchBatch, true);
- }
-
- protected void assertCatchBatch(CatchBatch expectedCatchBatch,CatchBatch actualCatchBatch, boolean assertIdEquals) {
- if (expectedCatchBatch == null) {
- assertNull(actualCatchBatch);
- return;
- }
-
- assertNotNull(actualCatchBatch);
- if (assertIdEquals) {
- assertEquals(expectedCatchBatch.getId(), actualCatchBatch.getId());
- }
- assertEquals(expectedCatchBatch.getCatchTotalWeight(), actualCatchBatch.getCatchTotalWeight());
- assertEquals(expectedCatchBatch.getCatchTotalSortedCarousselWeight(), actualCatchBatch.getCatchTotalSortedCarousselWeight());
- assertEquals(expectedCatchBatch.getCatchTotalSortedTremisWeight(), actualCatchBatch.getCatchTotalSortedTremisWeight());
- assertEquals(expectedCatchBatch.getCatchTotalUnsortedWeight(), actualCatchBatch.getCatchTotalUnsortedWeight());
-
- assertEquals(expectedCatchBatch.getSpeciesTotalSampleSortedWeight(), actualCatchBatch.getSpeciesTotalSampleSortedWeight());
- assertEquals(expectedCatchBatch.getSpeciesTotalSortedWeight(), actualCatchBatch.getSpeciesTotalSortedWeight());
- assertEquals(expectedCatchBatch.getSpeciesTotalUnsortedWeight(), actualCatchBatch.getSpeciesTotalUnsortedWeight());
- assertEquals(expectedCatchBatch.getSpeciesTotalInertWeight(), actualCatchBatch.getSpeciesTotalInertWeight());
- assertEquals(expectedCatchBatch.getSpeciesTotalLivingNotItemizedWeight(), actualCatchBatch.getSpeciesTotalLivingNotItemizedWeight());
- }
-
- protected void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
- assertNotNull(actualBatch);
- assertNotNull(actualBatch.getId());
- if (assertIdEquals && expectedBatch.getId() != null) {
- assertEquals(expectedBatch.getId(), actualBatch.getId());
- }
- assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
- assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
- if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
- assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
- actualBatch.getSampleCategoryValue());
- assertEquals(
- ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
- ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
- } else {
- assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
- }
- assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
- assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
- assertEquals(expectedBatch.getComment(), actualBatch.getComment());
-
- // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
- // (Because getSpeciesBatch(id) could not always retrieve the species)
- if (expectedBatch.getSpecies() != null && (
- expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
- || actualBatch.getSpecies() != null)) {
- assertNotNull(actualBatch.getSpecies());
- assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
- }
- }
- protected List<SpeciesBatchFrequency> assertCreateAndReloadSpeciesBatchFrequency(List<SpeciesBatchFrequency> frequencies, String parentBatchId) {
-
- // Create batch
- List<SpeciesBatchFrequency> createdFrequencies = service.saveSpeciesBatchFrequency(parentBatchId, frequencies);
- assertBatchFrequencies(frequencies, createdFrequencies, false);
-
- // then reload (for round trip check)
- List<SpeciesBatchFrequency> reloadedFrequencies = service.getAllSpeciesBatchFrequency(parentBatchId);
- assertBatchFrequencies(createdFrequencies, reloadedFrequencies, true);
-
- return createdFrequencies;
- }
-
- protected void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
- assertNotNull(actualFrequencies);
- assertEquals(expectedFrequencies.size(), actualFrequencies.size());
-
- // Store actual batches into a map, using the length as key
- Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
- for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
- expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
- }
-
- // Store expected batches into a map, using the length as key
- Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
- for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
- assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
- actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
- assertNotNull(speciesBatchFrequency.getId());
- }
-
- for (Float lengthStep : expectedLengthMap.keySet()) {
- SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
- SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
- if (assertIdEquals) {
- assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
- }
- assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
- assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
- assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
- assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
- assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
- //assertNotNull(expectedBatchFrequency.getBatch());
- //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
- }
- }
-
- protected SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
- return getSpeciesBatch(speciesBatchId, service.getAllRootSpeciesBatch(fishingOperationId));
- }
-
- protected SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
- if (speciesBatchs == null) {
- return null;
- }
- for (SpeciesBatch speciesBatch : speciesBatchs) {
- if (speciesBatchId.equals(speciesBatch.getId())) {
- return speciesBatch;
- }
- if (speciesBatch.getChildBatchs() != null) {
- speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
- if (speciesBatch != null) {
- return speciesBatch;
- }
- }
- }
- return null;
- }
-}
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.Cruise;
+import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
+import fr.ifremer.tutti.persistence.entities.referential.Species;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.springframework.dao.DataRetrievalFailureException;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.*;
+
+/**
+ * To test {@link CatchBatchPersistenceService} for write operation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class BatchPersistenceServiceWriteTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.writeDb();
+
+ protected BatchPersistenceService service;
+
+ protected CruisePersistenceService cruiseService;
+
+ protected FishingOperationPersistenceService fishingOperationService;
+
+ protected CatchBatchPersistenceService catchBatchService;
+
+ protected ReferentialPersistenceService referentialService;
+
+ protected Cruise cruise;
+
+ protected FishingOperation fishingOperationNoCatchBatch;
+
+ protected FishingOperation fishingOperationWithEmptyBatch;
+
+ protected CatchBatch catchBacth;
+
+ protected List<Species> species;
+
+ protected Caracteristic sortedUnsortedPMFM;
+
+ protected CaracteristicQualitativeValue horsVracQualitativeValue;
+
+ protected CaracteristicQualitativeValue vracQualitativeValue;
+
+ protected Caracteristic maturityPMFM;
+
+ protected CaracteristicQualitativeValue firstMaturityQualitativeValue;
+
+ protected Caracteristic sexPMFM;
+
+ protected CaracteristicQualitativeValue maleQualitativeValue;
+
+ protected CaracteristicQualitativeValue femaleQualitativeValue;
+
+ protected CaracteristicQualitativeValue unkQualitativeValue;
+
+ protected Caracteristic frequencyPMFM;
+
+ @Before
+ public void setUp() throws Exception {
+ service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
+ cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService();
+ fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
+ catchBatchService = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService();
+ referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService();
+
+ species = referentialService.getAllSpecies();
+ assertNotNull(species);
+ assertTrue(species.size() > 2);
+
+ cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId());
+ cruise.setId(null);
+ Calendar calendar = new GregorianCalendar();
+ cruise.setBeginDate(calendar.getTime());
+ cruise.setYear(calendar.get(Calendar.YEAR));
+ calendar.add(Calendar.MONTH, 1); // add one month
+ cruise.setEndDate(calendar.getTime());
+ cruise = cruiseService.createCruise(cruise);
+
+ // Create a first operation, with no cacth batch : to test CatchBatch insert/update :
+ List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
+ assertNotNull(fishingOperations);
+ assertTrue(fishingOperations.size() > 0);
+ fishingOperationNoCatchBatch = fishingOperations.get(0);
+ fishingOperationNoCatchBatch = fishingOperationService.getFishingOperation(fishingOperationNoCatchBatch.getId());
+ fishingOperationNoCatchBatch.setId(null);
+ fishingOperationNoCatchBatch.setCruise(cruise);
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 1);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationNoCatchBatch.setGearShootingStartDate(calendar.getTime());
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 10);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationNoCatchBatch.setGearShootingEndDate(calendar.getTime());
+ fishingOperationNoCatchBatch = fishingOperationService.createFishingOperation(fishingOperationNoCatchBatch);
+
+ // Create a second operation, with no cacth batch : to test CatchBatch insert/update :
+ fishingOperationWithEmptyBatch = fishingOperations.get(1);
+ fishingOperationWithEmptyBatch = fishingOperationService.getFishingOperation(fishingOperationWithEmptyBatch.getId());
+ fishingOperationWithEmptyBatch.setId(null);
+ fishingOperationWithEmptyBatch.setCruise(cruise);
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 11);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationWithEmptyBatch.setGearShootingStartDate(calendar.getTime());
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 12);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationWithEmptyBatch.setGearShootingEndDate(calendar.getTime());
+ fishingOperationWithEmptyBatch = fishingOperationService.createFishingOperation(fishingOperationWithEmptyBatch);
+
+ catchBacth = new CatchBatch();
+ catchBacth.setFishingOperation(fishingOperationWithEmptyBatch);
+ catchBacth = catchBatchService.createCatchBatch(catchBacth);
+
+ sortedUnsortedPMFM = referentialService.getSortedUnsortedCaracteristic();
+ horsVracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(0);
+ vracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(1);
+ maturityPMFM = referentialService.getMaturityCaracteristic();
+ firstMaturityQualitativeValue = maturityPMFM.getQualitativeValue(0);
+ sexPMFM = referentialService.getSexCaracteristic();
+ maleQualitativeValue = sexPMFM.getQualitativeValue(1);
+ femaleQualitativeValue = sexPMFM.getQualitativeValue(2);
+ unkQualitativeValue = sexPMFM.getQualitativeValue(3);
+
+ List<Caracteristic> cara = referentialService.getAllCaracteristic();
+ for (Caracteristic caracteristic : cara) {
+ if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER
+ && caracteristic.getPrecision() != null
+ && caracteristic.getPrecision() == 0.5f) {
+ frequencyPMFM = caracteristic;
+ break;
+ }
+ }
+ assertNotNull("no numerical PMFM with a precision has been found. Could not define a PMFM for batch frequencies.", frequencyPMFM);
+
+ }
+
+ @Test
+ public void createAndSaveCatchBatch() throws Exception {
+ CatchBatch catchBatch;
+
+ catchBatch = new CatchBatch();
+ catchBatch.setFishingOperation(fishingOperationNoCatchBatch);
+
+ // -----------------------------------------------------------------------------
+ // 1. Test with only mandatory properties
+ // -----------------------------------------------------------------------------
+
+ // Create and reload (test round trip)
+ assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 2. Test with all properties
+ // -----------------------------------------------------------------------------
+ catchBatch.setId(null);
+ // total weight : 100kg
+ catchBatch.setCatchTotalWeight(75f);
+ // Vrac :
+ {
+ // note : poids trie par la balance tremis (thalassa) (init par pupitri)
+ catchBatch.setCatchTotalSortedTremisWeight(50f);
+ // note : poids vrac caroussel (thalassa) (init par pupitri) (vrac trie) ou bien "poids trié fournie par la table de tri (Sum(Si)
+ catchBatch.setCatchTotalSortedCarousselWeight(45f);
+
+ // Species
+ {
+ catchBatch.setSpeciesTotalSortedWeight(12f);
+ catchBatch.setSpeciesTotalSampleSortedWeight(8f);
+ catchBatch.setSpeciesTotalLivingNotItemizedWeight(0.2f);
+ catchBatch.setSpeciesTotalInertWeight(0.1f);
+ }
+ }
+ // Hors Vrac : 10kg
+ {
+ catchBatch.setCatchTotalUnsortedWeight(10f);
+
+ // Species
+ {
+ catchBatch.setSpeciesTotalUnsortedWeight(10f);
+ }
+ }
+ // Rejet : 15kg
+ catchBatch.setCatchTotalRejectedWeight(15f);
+
+ // Create and reload (test round trip)
+ assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 2. Test save after modification
+ // -----------------------------------------------------------------------------
+ catchBatch.setCatchTotalSortedTremisWeight(null);
+ catchBatch.setCatchTotalSortedCarousselWeight(null);
+ catchBatch.setSpeciesTotalSortedWeight(null);
+ catchBatch.setSpeciesTotalSampleSortedWeight(null);
+ catchBatch.setCatchTotalUnsortedWeight(null);
+ catchBatch.setSpeciesTotalUnsortedWeight(null);
+
+ assertSaveAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+ }
+
+ @Test
+ public void createAndSaveSpeciesBatchAndFrequencies() {
+ SpeciesBatch esp1Batch = null;
+ SpeciesBatch esp2Batch = null;
+ SpeciesBatch frequenciesParentBatch = null;
+ SpeciesBatch batch = null;
+ Species taxon1 = species.get(0);
+ Species taxon2 = species.get(1);
+
+ // -----------------------------------------------------------------------------
+ // 1. Test with only mandatory properties
+ // -----------------------------------------------------------------------------
+ // batch : "ESP1 - Vrac/5"
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setFishingOperation(fishingOperationNoCatchBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(5f);
+
+ assertCreateAndReloadSpeciesBatch(batch, null);
+
+ // Save ESP1 batch
+ esp1Batch = batch;
+
+ // -----------------------------------------------------------------------------
+ // 2. Test child "Male/2"
+ // -----------------------------------------------------------------------------
+ // Batch : ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp1Batch);
+ batch.setSpecies(taxon1);
+ batch.setComment("ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(maleQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ batch.setWeight(1f);
+ batch.setNumber(7);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 3. Test child "Female/2"
+ // -----------------------------------------------------------------------------
+ // Batch : ESP1 - Vrac/5 Female/3 Nombre/14
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp1Batch);
+ batch.setSpecies(taxon1);
+ batch.setComment("ESP1 - Vrac/5 Female/3 Nombre/14");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(femaleQualitativeValue);
+ batch.setSampleCategoryWeight(3f);
+ batch.setWeight(null);
+ batch.setNumber(14);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 4. Test : ESP2 - Vrac/7
+ // \- ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
+ // -----------------------------------------------------------------------------
+ // batch : "ESP2 - Vrac/7 "
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setSpecies(taxon2);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(7f);
+
+ assertCreateAndReloadSpeciesBatch(batch, null);
+ esp2Batch = batch;
+
+ // Batch : ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp2Batch);
+ batch.setSpecies(taxon2);
+ batch.setComment("ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11");
+ batch.setSampleCategoryType(SampleCategoryEnum.maturity);
+ batch.setSampleCategoryValue(firstMaturityQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ batch.setWeight(1f);
+ batch.setNumber(11);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 5. Test save after modifications
+ // -----------------------------------------------------------------------------
+ // Batch : ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99
+ batch.setComment("ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(unkQualitativeValue);
+ batch.setSampleCategoryWeight(1.75f);
+ batch.setWeight(1.11f);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setNumber(99);
+
+ // Save and reload, then check
+ SpeciesBatch savedBatch = service.saveSpeciesBatch(batch);
+ assertSpeciesBatch(savedBatch, batch, false);
+ SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), savedBatch.getId());
+ assertSpeciesBatch(savedBatch, reloadedBatch, true);
+
+ // Save batch for later
+ frequenciesParentBatch = batch;
+
+ // -----------------------------------------------------------------------------
+ // 6. Test change species
+ // -----------------------------------------------------------------------------
+ esp2Batch.setSpecies(taxon1);
+ service.changeSpeciesBatchSpecies(esp2Batch.getId(), taxon1);
+ assertSpeciesBatch(savedBatch, batch, false);
+ reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp2Batch.getId());
+ assertSpeciesBatch(esp2Batch, reloadedBatch, true);
+
+ // -----------------------------------------------------------------------------
+ // 7. Test get all root species
+ // -----------------------------------------------------------------------------
+ List<SpeciesBatch> rootSpeciesBatch = service.getAllRootSpeciesBatch(fishingOperationWithEmptyBatch.getId());
+ assertNotNull(rootSpeciesBatch);
+ assertEquals(2, rootSpeciesBatch.size());
+ assertNotNull(rootSpeciesBatch.get(0).getChildBatchs());
+ assertTrue(rootSpeciesBatch.get(0).getChildBatchs().size() > 0);
+ assertNotNull(rootSpeciesBatch.get(1).getChildBatchs());
+ assertTrue(rootSpeciesBatch.get(1).getChildBatchs().size() > 0);
+
+ // -----------------------------------------------------------------------------
+ // 8. Test batch frequency creation
+ // -----------------------------------------------------------------------------
+
+ List<SpeciesBatchFrequency> frequencies = Lists.newArrayList();
+ float lengthStep = 0.5f;
+ for (float length = lengthStep; length < lengthStep * 20; length += lengthStep) {
+ SpeciesBatchFrequency frequency = new SpeciesBatchFrequency();
+ frequency.setLengthStep(length);
+ frequency.setNumber((int) (length * 2));
+ frequency.setWeight(0.01f * length * 2);
+ frequency.setLengthStepCaracteristic(frequencyPMFM);
+ frequency.setBatch(frequenciesParentBatch);
+ frequency.setComment("comments");
+ frequencies.add(frequency);
+ }
+ List<SpeciesBatchFrequency> createdFrequencies = assertCreateAndReloadSpeciesBatchFrequency(frequencies, frequenciesParentBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 9. Test batch frequency update
+ // -----------------------------------------------------------------------------
+ // Update some batchs (1cm, 2cm, etc)
+ for (SpeciesBatchFrequency speciesBatchFrequency : createdFrequencies) {
+ float length = speciesBatchFrequency.getLengthStep();
+ if ((float) (int) length == length) {
+ speciesBatchFrequency.setNumber(12);
+ speciesBatchFrequency.setComment(null);
+ }
+ }
+ // And remove the last item (should be deleted in DB)
+ createdFrequencies.remove(createdFrequencies.size()-1);
+ List<SpeciesBatchFrequency> savedFrequencies = service.saveSpeciesBatchFrequency(frequenciesParentBatch.getId(), frequencies);
+ assertBatchFrequencies(createdFrequencies, savedFrequencies, true);
+ }
+
+ @Test
+ public void deleteSpeciesBatch(/*String id*/) {
+ SpeciesBatch esp1Batch;
+ SpeciesBatch batch;
+ Species taxon1 = species.get(0);
+
+ // -----------------------------------------------------------------------------
+ // 1. Create two batchs (parent + child), then remove the parent batch
+ // -----------------------------------------------------------------------------
+ // batch : ESP1 Vrac/5
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(5f);
+ assertCreateAndReloadSpeciesBatch(batch, null);
+ esp1Batch = batch;
+
+ // batch : ESP1 Vrac/5 Male/2
+ batch = new SpeciesBatch();
+ batch.setParentBatch(esp1Batch);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(maleQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ assertCreateAndReloadSpeciesBatch(batch, esp1Batch.getId());
+
+ // Try to remove
+ service.deleteSpeciesBatch(esp1Batch.getId());
+
+ // Check if remove
+ try {
+ batch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp1Batch.getId());
+ assertNull(batch);
+ } catch (DataRetrievalFailureException drfe) {
+ assertNotNull(drfe);
+ }
+ }
+
+ protected void assertCreateAndReloadSpeciesBatch(SpeciesBatch batch, String parentBatchId) {
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+
+ // Create batch
+ SpeciesBatch createdBatch = service.createSpeciesBatch(batch, parentBatchId);
+ assertSpeciesBatch(batch, createdBatch, false);
+
+ // then reload (for round trip check)
+ SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), createdBatch.getId());
+ if (parentBatchId == null) {
+ assertNull(reloadedBatch.getParentBatch());
+ } else {
+ assertNotNull(reloadedBatch.getParentBatch());
+ assertEquals(parentBatchId, reloadedBatch.getParentBatch().getId());
+ }
+ assertSpeciesBatch(createdBatch, reloadedBatch, false);
+
+ batch.setId(createdBatch.getId());
+ }
+
+ protected void assertCreateAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
+ CatchBatch createdCatchBatch = service.createCatchBatch(catchBatch);
+ assertNotNull(createdCatchBatch);
+ assertNotNull(createdCatchBatch.getId());
+ assertCatchBatch(catchBatch, createdCatchBatch, false);
+
+ CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
+ assertCatchBatch(createdCatchBatch, reloadedCatchBatch, true);
+
+ catchBatch.setId(createdCatchBatch.getId());
+ }
+
+ protected void assertSaveAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
+ CatchBatch savedCatchBatch = service.saveCatchBatch(catchBatch);
+ assertNotNull(savedCatchBatch);
+ assertNotNull(savedCatchBatch.getId());
+ assertCatchBatch(catchBatch, savedCatchBatch, false);
+
+ CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
+ assertCatchBatch(savedCatchBatch, reloadedCatchBatch, true);
+ }
+
+ protected void assertCatchBatch(CatchBatch expectedCatchBatch,CatchBatch actualCatchBatch, boolean assertIdEquals) {
+ if (expectedCatchBatch == null) {
+ assertNull(actualCatchBatch);
+ return;
+ }
+
+ assertNotNull(actualCatchBatch);
+ if (assertIdEquals) {
+ assertEquals(expectedCatchBatch.getId(), actualCatchBatch.getId());
+ }
+ assertEquals(expectedCatchBatch.getCatchTotalWeight(), actualCatchBatch.getCatchTotalWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalSortedCarousselWeight(), actualCatchBatch.getCatchTotalSortedCarousselWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalSortedTremisWeight(), actualCatchBatch.getCatchTotalSortedTremisWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalUnsortedWeight(), actualCatchBatch.getCatchTotalUnsortedWeight());
+
+ assertEquals(expectedCatchBatch.getSpeciesTotalSampleSortedWeight(), actualCatchBatch.getSpeciesTotalSampleSortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalSortedWeight(), actualCatchBatch.getSpeciesTotalSortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalUnsortedWeight(), actualCatchBatch.getSpeciesTotalUnsortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalInertWeight(), actualCatchBatch.getSpeciesTotalInertWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalLivingNotItemizedWeight(), actualCatchBatch.getSpeciesTotalLivingNotItemizedWeight());
+ }
+
+ protected void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
+ assertNotNull(actualBatch);
+ assertNotNull(actualBatch.getId());
+ if (assertIdEquals && expectedBatch.getId() != null) {
+ assertEquals(expectedBatch.getId(), actualBatch.getId());
+ }
+ assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
+ assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
+ if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
+ assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
+ actualBatch.getSampleCategoryValue());
+ assertEquals(
+ ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
+ ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
+ } else {
+ assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
+ }
+ assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
+ assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
+ assertEquals(expectedBatch.getComment(), actualBatch.getComment());
+
+ // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
+ // (Because getSpeciesBatch(id) could not always retrieve the species)
+ if (expectedBatch.getSpecies() != null && (
+ expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
+ || actualBatch.getSpecies() != null)) {
+ assertNotNull(actualBatch.getSpecies());
+ assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
+ }
+ }
+ protected List<SpeciesBatchFrequency> assertCreateAndReloadSpeciesBatchFrequency(List<SpeciesBatchFrequency> frequencies, String parentBatchId) {
+
+ // Create batch
+ List<SpeciesBatchFrequency> createdFrequencies = service.saveSpeciesBatchFrequency(parentBatchId, frequencies);
+ assertBatchFrequencies(frequencies, createdFrequencies, false);
+
+ // then reload (for round trip check)
+ List<SpeciesBatchFrequency> reloadedFrequencies = service.getAllSpeciesBatchFrequency(parentBatchId);
+ assertBatchFrequencies(createdFrequencies, reloadedFrequencies, true);
+
+ return createdFrequencies;
+ }
+
+ protected void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
+ assertNotNull(actualFrequencies);
+ assertEquals(expectedFrequencies.size(), actualFrequencies.size());
+
+ // Store actual batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
+ expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ }
+
+ // Store expected batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
+ assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
+ actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ assertNotNull(speciesBatchFrequency.getId());
+ }
+
+ for (Float lengthStep : expectedLengthMap.keySet()) {
+ SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
+ SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
+ if (assertIdEquals) {
+ assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
+ }
+ assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
+ assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
+ assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
+ assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
+ assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
+ //assertNotNull(expectedBatchFrequency.getBatch());
+ //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
+ }
+ }
+
+ protected SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
+ return getSpeciesBatch(speciesBatchId, service.getAllRootSpeciesBatch(fishingOperationId));
+ }
+
+ protected SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
+ if (speciesBatchs == null) {
+ return null;
+ }
+ for (SpeciesBatch speciesBatch : speciesBatchs) {
+ if (speciesBatchId.equals(speciesBatch.getId())) {
+ return speciesBatch;
+ }
+ if (speciesBatch.getChildBatchs() != null) {
+ speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
+ if (speciesBatch != null) {
+ return speciesBatch;
+ }
+ }
+ }
+ return null;
+ }
+}
Property changes on: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelperTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -631,82 +631,6 @@
updateTable(TuttiTable.AGGREGATION_LEVEL, internalDb, internalConnection, externalConnection, fromDate, 1, 0);
}
- @Test
- public void synchronize() throws IOException, SQLException {
-
- createInternalConnection();
-
- TuttiDatabaseMetadata internalDb =
- helper.loadDatabaseMetadata(internalConnection, dialect);
- Assert.assertNotNull(internalDb);
-
- createExternalDb();
-
- // synchronize from main db to empty db
-
- ReferentialSynchronizeResult result =
- helper.synchronize(externalConnectionProperties,
- localConnectionProperties,
- dialect);
-
- // same referentiel in both db
- Assert.assertNotNull(result);
- Assert.assertNull(result.getError());
-
- DatabaseSynchroFixtures fixturesExternal;
- DatabaseSynchroFixtures fixturesInternal;
-
- fixturesInternal = new DatabaseSynchroFixtures(
- helper, internalDb, internalConnection);
- fixturesExternal = new DatabaseSynchroFixtures(
- helper, internalDb, externalConnection);
-
- for (TuttiTable tuttiTable : TuttiTable.values()) {
- String tableName = tuttiTable.name();
- int nbInserts = result.getNbInserts(tableName);
- int nbUpdates = result.getNbUpdates(tableName);
- int expected = fixturesInternal.count(tuttiTable);
- Assert.assertEquals(String.format("Table %s Should found %s inserts, but was only %s", tableName, expected, nbInserts), expected, nbInserts, 0);
- Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, 0, nbUpdates), 0, nbUpdates, 0);
- Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, fixturesInternal.count(tuttiTable), nbUpdates), fixturesInternal.count(tuttiTable), fixturesExternal.count(tuttiTable), 0);
- }
-
- // add a new status
- internalConnection.prepareStatement("INSERT INTO STATUS(CODE, NAME) VALUES (4, 'NEW')").executeUpdate();
-
- // add a new aggregation_level
- internalConnection.prepareStatement("INSERT INTO AGGREGATION_LEVEL (ID, NAME, RANK_ORDER, UPDATE_DATE) VALUES (-1000, 'NAME', -1000, NULL)").executeUpdate();
-
- // update a unit
- PreparedStatement preparedStatement = internalConnection.prepareStatement("UPDATE UNIT SET SYMBOL = 'Auncun un?', UPDATE_DATE=? WHERE ID=1");
- preparedStatement.setDate(1, new java.sql.Date(System.currentTimeMillis()));
- preparedStatement.executeUpdate();
-
- internalConnection.commit();
-
- fixturesInternal = new DatabaseSynchroFixtures(
- helper, internalDb, internalConnection);
-
- result = helper.synchronize(externalConnectionProperties,
- localConnectionProperties,
- dialect);
- Assert.assertNotNull(result);
- Assert.assertNull(result.getError());
-
- fixturesExternal = new DatabaseSynchroFixtures(
- helper, internalDb, externalConnection);
-
- for (TuttiTable tuttiTable : TuttiTable.values()) {
- String tableName = tuttiTable.name();
-
- int internalCount = fixturesInternal.count(tuttiTable);
- int externalCount = fixturesExternal.count(tuttiTable);
-
- Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, internalCount, externalCount), internalCount, externalCount, 0);
- }
-
- }
-
protected ResultSet getDataToUpdate(TuttiTable tuttiTable,
TuttiDatabaseMetadata db,
Connection connection,
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -25,6 +25,7 @@
*/
import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.ProgressionModel;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
import fr.ifremer.tutti.persistence.service.TuttiPersistenceServiceLocator;
import org.hibernate.dialect.Dialect;
@@ -37,6 +38,12 @@
import org.junit.rules.TestName;
import org.springframework.jdbc.support.JdbcUtils;
+import javax.swing.JDialog;
+import javax.swing.JProgressBar;
+import java.awt.Frame;
+import java.awt.GraphicsEnvironment;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@@ -69,6 +76,8 @@
protected ReferentialSynchronizeHelper helper;
+ protected JDialog dialog;
+
@Before
public void setUp() throws Exception {
@@ -91,6 +100,9 @@
@After
public void tearDown() throws Exception {
+ if (dialog != null) {
+ dialog.setVisible(false);
+ }
service = null;
remoteConnectionProperties = null;
dialect = null;
@@ -107,7 +119,6 @@
DatabaseSynchroFixtures fixturesRemote;
DatabaseSynchroFixtures fixturesLocal;
- ReferentialSynchronizeResult result;
// add some stuff on remote db
@@ -127,12 +138,69 @@
fixturesRemote = new DatabaseSynchroFixtures(
helper, remoteSchema, remoteConnection);
- result = service.synchronize(remoteConnectionProperties);
+ fixturesLocal = new DatabaseSynchroFixtures(
+ helper, remoteSchema, localConnection);
- // same referentiel in both db
+ ReferentialSynchronizeResult result =
+ new ReferentialSynchronizeResult();
+
+
+ dialog = createProgressBar(result);
+
+ service.prepare(remoteConnectionProperties, result);
+
Assert.assertNotNull(result);
Assert.assertNull(result.getError());
+ Assert.assertTrue(result.isSuccess());
+ // on entities, only updates in table is with no update_date
+ for (TuttiTable tuttiTable : TuttiTable.getEntityTables()) {
+ String tableName = tuttiTable.name();
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int nbRows = result.getNbRows(tableName);
+ int expectedRows = 0;
+ TuttiTableMetadata table = remoteSchema.getTable(tableName);
+ if (!table.isWithUpdateDateColumn()) {
+ // updates everything
+ expectedRows = nbRemote;
+ }
+
+ switch (tuttiTable) {
+ case STATUS:
+ nbLocal++;
+ break;
+
+ case UNIT:
+ expectedRows = 1;
+ break;
+
+ case AGGREGATION_LEVEL:
+ nbLocal++;
+ expectedRows = 1;
+ break;
+ }
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows to treat, but was only %s", tableName, expectedRows, nbRows), expectedRows, nbRows, 0);
+ }
+
+ // on associations, only inserts
+ for (TuttiTable tuttiTable : TuttiTable.getAssociationTables()) {
+ String tableName = tuttiTable.name();
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int nbRows = result.getNbRows(tableName);
+ int expectedRows = nbRemote;
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows to treat, but was only %s", tableName, expectedRows, nbRows), expectedRows, nbRows, 0);
+ }
+
+ service.synchronize(remoteConnectionProperties, result);
+
+ Assert.assertEquals(result.getTotalRows(), result.getProgressionModel().getTotal());
+ Assert.assertEquals(result.getProgressionModel().getTotal(), result.getProgressionModel().getCurrent());
+ Assert.assertEquals(1.0, result.getProgressionModel().getRate(), 0.01);
+
fixturesLocal = new DatabaseSynchroFixtures(
helper, remoteSchema, localConnection);
@@ -187,6 +255,45 @@
Assert.assertEquals(String.format("Table %s Should found %s updates, but was only %s", tableName, expectedUpdates, nbUpdates), expectedUpdates, nbUpdates, 0);
Assert.assertEquals(String.format("Table %s Should found %s rows treated, but was only %s", tableName, expectedRows, nbInserts + nbUpdates), expectedRows, nbInserts + nbUpdates, 0);
}
+ }
+ public static JDialog createProgressBar(ReferentialSynchronizeResult result) {
+
+ JDialog dialog;
+ if (GraphicsEnvironment.isHeadless()) {
+ dialog = null;
+ } else {
+ dialog = new JDialog((Frame) null,
+ "synchronisation " + result.getLocalUrl() + " from " + result.getRemoteUrl(),
+ false);
+ dialog.setSize(600, 400);
+ final JProgressBar progressBar = new JProgressBar();
+ progressBar.setStringPainted(true);
+ progressBar.setIndeterminate(false);
+ ProgressionModel progressionModel = result.getProgressionModel();
+ progressionModel.addPropertyChangeListener(ProgressionModel.PROPERTY_MESSAGE, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ progressBar.setString((String) evt.getNewValue());
+ }
+ });
+ progressionModel.addPropertyChangeListener(ProgressionModel.PROPERTY_TOTAL, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ progressBar.setMinimum(0);
+ progressBar.setMaximum((Integer) evt.getNewValue());
+ }
+ });
+ progressionModel.addPropertyChangeListener(ProgressionModel.PROPERTY_CURRENT, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ progressBar.setValue((Integer) evt.getNewValue());
+
+ }
+ });
+ dialog.add(progressBar);
+ dialog.setVisible(true);
+ }
+ return dialog;
}
}
Modified: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java 2013-02-14 15:27:16 UTC (rev 413)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeServiceImplUpTodateTest.java 2013-02-14 23:53:34 UTC (rev 414)
@@ -37,6 +37,8 @@
import org.junit.rules.TestName;
import org.springframework.jdbc.support.JdbcUtils;
+import javax.swing.JDialog;
+import java.awt.GraphicsEnvironment;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
@@ -67,6 +69,8 @@
protected ReferentialSynchronizeHelper helper;
+ protected JDialog dialog;
+
@Before
public void setUp() throws Exception {
@@ -89,6 +93,9 @@
@After
public void tearDown() throws Exception {
+ if (dialog!=null) {
+ dialog.setVisible(false);
+ }
service = null;
remoteConnectionProperties = null;
dialect = null;
@@ -105,17 +112,53 @@
DatabaseSynchroFixtures fixturesRemote;
DatabaseSynchroFixtures fixturesLocal;
- ReferentialSynchronizeResult result;
fixturesRemote = new DatabaseSynchroFixtures(
helper, remoteSchema, remoteConnection);
- result = service.synchronize(remoteConnectionProperties);
+ fixturesLocal = new DatabaseSynchroFixtures(
+ helper, remoteSchema, localConnection);
- // same referentiel in both db
+ ReferentialSynchronizeResult result = new ReferentialSynchronizeResult();
+
+ dialog = ReferentialSynchronizeServiceImplTest.createProgressBar(result);
+
+ service.prepare(remoteConnectionProperties, result);
+
Assert.assertNotNull(result);
Assert.assertNull(result.getError());
+ Assert.assertTrue(result.isSuccess());
+ // on entities, only updates in table is with no update_date
+ for (TuttiTable tuttiTable : TuttiTable.getEntityTables()) {
+ String tableName = tuttiTable.name();
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int nbRows = result.getNbRows(tableName);
+ int expectedRows = 0;
+ TuttiTableMetadata table = remoteSchema.getTable(tableName);
+ if (!table.isWithUpdateDateColumn()) {
+ // updates everything
+ expectedRows = nbRemote;
+ }
+
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows to treat, but was only %s", tableName, expectedRows, nbRows), expectedRows, nbRows, 0);
+ }
+
+ // on associations, only inserts
+ for (TuttiTable tuttiTable : TuttiTable.getAssociationTables()) {
+ String tableName = tuttiTable.name();
+ int nbLocal = fixturesLocal.count(tuttiTable);
+ int nbRemote = fixturesRemote.count(tuttiTable);
+ int nbRows = result.getNbRows(tableName);
+ int expectedRows = nbRemote;
+ Assert.assertEquals(String.format("Table %s Should found %s rows, but was only %s", tableName, nbRemote, nbLocal), nbRemote, nbLocal, 0);
+ Assert.assertEquals(String.format("Table %s Should found %s rows to treat, but was only %s", tableName, expectedRows, nbRows), expectedRows, nbRows, 0);
+ }
+
+ service.synchronize(remoteConnectionProperties, result);
+
fixturesLocal = new DatabaseSynchroFixtures(
helper, remoteSchema, localConnection);
1
0
r413 - in trunk/tutti-persistence/src: main/java/fr/ifremer/tutti/persistence/service main/java/fr/ifremer/tutti/persistence/service/measure main/resources main/resources/i18n test/java/fr/ifremer/tutti/persistence/service
by blavenier@users.forge.codelutin.com 14 Feb '13
by blavenier@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: blavenier
Date: 2013-02-14 16:27:16 +0100 (Thu, 14 Feb 2013)
New Revision: 413
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/413
Log:
Fix :
- saveBatchFrequencies now delete extra batch
- store weights for 'inert' and 'livingNotSorted'
Add :
- ReferentialPersistenceService.getSampleCategoryIds()
Improve :
- Merge CatchBatchPersistenceService and SpeciesBatchPersistenceService into BatchPersistenceService
- batch management now use adagio implementation CatchBatchExtendDao
Added:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
Removed:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java
Modified:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/measure/MeasurementPersistenceHelper.java
trunk/tutti-persistence/src/main/resources/applicationContext-service-tutti.xml
trunk/tutti-persistence/src/main/resources/i18n/tutti-persistence_fr_FR.properties
trunk/tutti-persistence/src/main/resources/queries-override.hbm.xml
trunk/tutti-persistence/src/main/resources/tutti-db-conf.properties
trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -38,6 +38,7 @@
import java.io.Serializable;
import java.util.Iterator;
+import java.util.List;
/**
* TODO
@@ -123,6 +124,13 @@
return result;
}
+ protected <T> List<T> queryList2Typed(String queryName, Object... params) {
+
+ Query query = createQuery(queryName, params);
+ List result = query.list();
+ return result;
+ }
+
protected Query createQuery(String queryName, Object... params) {
Query query = getCurrentSession().getNamedQuery(queryName);
Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceService.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -0,0 +1,8 @@
+package fr.ifremer.tutti.persistence.service;
+
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional(readOnly = true)
+public interface BatchPersistenceService extends CatchBatchPersistenceService, SpeciesBatchPersistenceService{
+
+}
Added: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java (rev 0)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -0,0 +1,1297 @@
+package fr.ifremer.tutti.persistence.service;
+
+import static org.nuiton.i18n.I18n._;
+
+import java.io.Serializable;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.annotation.Resource;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.FlushMode;
+import org.hibernate.type.IntegerType;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.DataRetrievalFailureException;
+import org.springframework.stereotype.Service;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+import fr.ifremer.adagio.core.dao.data.batch.Batch;
+import fr.ifremer.adagio.core.dao.data.batch.CatchBatchExtendDao;
+import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
+import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
+import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationError;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidationException;
+import fr.ifremer.adagio.core.dao.data.batch.validator.CatchBatchValidator;
+import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
+import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
+import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
+import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
+import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
+import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
+import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
+import fr.ifremer.tutti.persistence.entities.referential.Species;
+import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
+
+@Service("batchPersistenceService")
+public class BatchPersistenceServiceImpl
+ extends AbstractPersistenceService implements BatchPersistenceService, CatchBatchValidator
+ {
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(BatchPersistenceServiceImpl.class);
+
+ @Resource(name = "referentialPersistenceService")
+ protected ReferentialPersistenceService referentialService;
+
+ @Resource(name = "denormalizedBatchDao")
+ protected DenormalizedBatchDao denormalizedBatchDao;
+
+ @Resource(name = "sortingBatchDao")
+ protected SortingBatchDao sortingBatchDao;
+
+ @Resource(name = "catchBatchDao")
+ protected CatchBatchExtendDao catchBatchDao;
+
+ @Resource(name = "measurementPersistenceHelper")
+ protected MeasurementPersistenceHelper measurementHelper;
+
+ @Override
+ public void init() {
+ super.init();
+ catchBatchDao.registerCatchBatchValidator(this);
+ }
+
+ @Override
+ public void close() {
+ catchBatchDao.unregisterCatchBatchValidator(this);
+ super.close();
+ }
+
+ @Override
+ public boolean isEnable(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+ // Apply validation only on catch batch for fishingOperation
+ return (catchBatch.getFishingOperation() != null);
+ }
+
+ @Override
+ public List<CatchBatchValidationError> validate(fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+ List<CatchBatchValidationError> errors = Lists.newArrayList();
+ validate(catchBatch.getChildBatchs(), errors, 1);
+ return errors;
+ }
+
+ @Override
+ public CatchBatch getCatchBatchFromFishingOperation(String fishingOperationId) {
+ Preconditions.checkNotNull(fishingOperationId);
+
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
+
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch source;
+ try {
+ source = catchBatchDao.loadFullTree(catchBatchId, true, true);
+ } catch (CatchBatchValidationException e) {
+ throw new DataRetrievalFailureException("Invalid batch tree structure, for fishing operation id=" + fishingOperationId, e);
+ }
+
+ CatchBatch result = new CatchBatch();
+ result.setId(source.getId().toString());
+ result.setCatchTotalWeight(source.getWeight());
+
+ // Vrac
+ SortingBatch vracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID);
+ result.setCatchTotalSortedCarousselWeight(vracBatch.getWeight());
+ result.setCatchTotalSortedTremisWeight(vracBatch.getWeightBeforeSampling());
+ {
+ // Species
+ SortingBatch speciesBatch = catchBatchDao.getSortingBatch(vracBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ result.setSpeciesTotalSampleSortedWeight(speciesBatch.getWeight());
+ result.setSpeciesTotalSortedWeight(speciesBatch.getWeightBeforeSampling());
+
+ {
+ // Inert
+ SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
+ "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
+ result.setSpeciesTotalInertWeight(inertBatch.getWeight());
+
+ // Alive no itemized
+ SortingBatch livingNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(),
+ "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
+ result.setSpeciesTotalLivingNotItemizedWeight(livingNotItemizedBatch.getWeight());
+ }
+
+ // TODO : Benthos, Plancton...
+ }
+
+ // Hors Vrac
+ SortingBatch horsVracBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID);
+ result.setCatchTotalUnsortedWeight(horsVracBatch.getWeight());
+ {
+ // Species
+ SortingBatch speciesBatch = catchBatchDao.getSortingBatch(horsVracBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ result.setSpeciesTotalUnsortedWeight(speciesBatch.getWeight());
+
+ // TODO : Benthos, Plancton...
+ }
+
+ // Non trié
+ SortingBatch unsortedBatch = catchBatchDao.getSortingBatch(source.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID);
+ result.setCatchTotalRejectedWeight(unsortedBatch.getWeight());
+
+ return result;
+ }
+
+ @Override
+
+ public CatchBatch createCatchBatch(CatchBatch bean) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkArgument(bean.getId() == null);
+ Preconditions.checkNotNull(bean.getFishingOperation());
+ Preconditions.checkNotNull(bean.getFishingOperation().getId());
+
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = fr.ifremer.adagio.core.dao.data.batch.CatchBatch.Factory.newInstance();
+ beanToEntity(bean, catchBatch, true);
+ catchBatch = catchBatchDao.create(catchBatch);
+ bean.setId(String.valueOf(catchBatch.getId()));
+
+ // Link to fishing operation
+ getCurrentSession().flush();
+ Integer fishingOperationId = Integer.valueOf(bean.getFishingOperation().getId());
+ int rowUpdated = queryUpdate("updateFishingOperationCatchBatch",
+ "fishingOperationId", IntegerType.INSTANCE, fishingOperationId,
+ "catchBatchId", IntegerType.INSTANCE, catchBatch.getId());
+ if (rowUpdated == 0) {
+ throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found.");
+ }
+
+ return bean;
+ }
+
+ @Override
+ @CacheEvict(value = "batchTree", key="#bean.fishingOperation.id")
+ public CatchBatch saveCatchBatch(CatchBatch bean) {
+
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkNotNull(bean.getId());
+
+ getCurrentSession().enableFetchProfile("batch-with-childs");
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(Integer.valueOf(bean.getId()));
+ if (catchBatch == null) {
+ throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId());
+ }
+
+ beanToEntity(bean, catchBatch, true);
+ catchBatchDao.update(catchBatch);
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) {
+
+ // Load batch tree
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(fishingOperationId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ List<SpeciesBatch> result = new ArrayList<SpeciesBatch>();
+
+ // Vrac / Species
+ SortingBatch vracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ for (Iterator<Batch> iterator = vracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+
+ // evict some special batches : Life (or Biota) and Inert
+ if (source.getReferenceTaxon() != null
+ && enumeration.REFERENCE_TAXON_ID_LIFE.equals(source.getReferenceTaxon().getId()) == false
+ && enumeration.REFERENCE_TAXON_ID_INERT.equals(source.getReferenceTaxon().getId()) == false) {
+ SpeciesBatch target = new SpeciesBatch();
+
+ entityToBean(source, target);
+ result.add(target);
+ }
+ }
+
+ // Hors-Vrac / Species
+ SortingBatch horsVracSpeciesBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ for (Iterator<Batch> iterator = horsVracSpeciesBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+
+ SpeciesBatch target = new SpeciesBatch();
+
+ entityToBean(source, target);
+ result.add(target);
+ }
+
+ return result;
+ }
+
+ protected SpeciesBatch entityToBean(SortingBatch source, SpeciesBatch target) {
+
+ target.setId(source.getId().toString());
+
+ // Individual count
+ target.setNumber(source.getIndividualCount());
+
+ // Convert database weight (and sampling ratio) into UI weight and sampleCategoryWeight
+ if (source.getWeight() != null && source.getWeightBeforeSampling() == null) {
+ target.setSampleCategoryWeight(source.getWeight());
+ }
+ else {
+ target.setWeight(source.getWeight());
+ target.setSampleCategoryWeight(source.getWeightBeforeSampling());
+ }
+
+ // Comments
+ target.setComment(source.getComments());
+
+ // Sample category type (only one is applied)
+ SortingMeasurement sm = null;
+ if (source.getSortingMeasurements().size() == 1) {
+ sm = source.getSortingMeasurements().iterator().next();
+ }
+ else if (source.getReferenceTaxon() != null && source.getReferenceTaxon().getId() != null){
+ sm = measurementHelper.getInheritedSortingMeasurement(source, enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+ if (sm != null) {
+ SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(sm.getPmfm().getId());
+ if (sampleCategory != null) {
+ setSampleCategoryQualitative(target, sm.getPmfm().getId(), sm.getNumericalValue(), sm.getAlphanumericalValue(), sm.getQualitativeValue().getId());
+ }
+ }
+
+ // Species
+ Integer referenceTaxonId = source.getInheritedReferenceTaxonId();
+ if (referenceTaxonId == null && source.getReferenceTaxon() != null) {
+ referenceTaxonId = source.getReferenceTaxon().getId();
+ }
+ if (referenceTaxonId != null) {
+ // TODO : add cache on getSpeciesByReferenceTaxonId
+ Species species = referentialService.getSpeciesByReferenceTaxonId(referenceTaxonId);
+ target.setSpecies(species);
+ }
+
+ if (target.getSampleCategoryType() != null && source.getChildBatchs().size() > 0) {
+ List<SpeciesBatch> targetChilds = Lists.newArrayList();
+ for (Iterator<Batch> iterator = source.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch sourceChild = (SortingBatch) iterator.next();
+ SpeciesBatch targetChild = new SpeciesBatch();
+ entityToBean(sourceChild, targetChild);
+ if (targetChild.getSampleCategoryValue() != null) {
+ targetChilds.add(targetChild);
+ targetChild.setParentBatch(target);
+ }
+ }
+ target.setChildBatchs(targetChilds);
+ }
+
+ return target;
+ }
+
+ @Override
+ public SpeciesBatch createSpeciesBatch(SpeciesBatch bean,
+ String parentBatchId) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkArgument(bean.getId() == null);
+ Preconditions.checkNotNull(bean.getSpecies());
+ Preconditions.checkNotNull(bean.getSpecies().getId());
+ Preconditions.checkNotNull(bean.getFishingOperation());
+ Preconditions.checkNotNull(bean.getFishingOperation().getId());
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ // Load full batch tree
+ Integer catchBatchId = catchBatchDao.getIdByFishingOperationId(Integer.valueOf(bean.getFishingOperation().getId()));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ SortingBatch batch = SortingBatch.Factory.newInstance();
+ beanToEntity(bean, batch, parentBatchId, catchBatch, true);
+ batch = sortingBatchDao.create(batch);
+
+ bean.setId(String.valueOf(batch.getId()));
+
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) {
+ Preconditions.checkNotNull(bean);
+ Preconditions.checkNotNull(bean.getId());
+
+ // Load full batch tree
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(bean.getId()));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ SortingBatch batch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(bean.getId()));
+ String parentBatchId = null;
+ if (bean.getParentBatch() != null) {
+ parentBatchId = bean.getParentBatch().getId();
+ }
+ beanToEntity(bean, batch, parentBatchId, catchBatch, true);
+ sortingBatchDao.update(batch);
+ getCurrentSession().flush();
+
+ return bean;
+ }
+
+ @Override
+ public void deleteSpeciesBatch(String id) {
+ Preconditions.checkNotNull(id);
+
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ catchBatchDao.removeWithChildren(Integer.valueOf(id));
+
+ getCurrentSession().flush();
+ }
+
+ public void deleteSpeciesSubBatch(String id) {
+ deleteSpeciesBatch(id);
+ }
+
+ public void changeSpeciesBatchSpecies(String batchId, Species species) {
+ Preconditions.checkNotNull(batchId);
+ Preconditions.checkNotNull(species);
+ Preconditions.checkNotNull(species.getReferenceTaxonId());
+
+ if (log.isDebugEnabled()) {
+ log.debug("Changing species for batch id=" + batchId);
+ }
+
+ int rowUpdated = queryUpdate("updateBatchSpecies",
+ "batchId", IntegerType.INSTANCE, Integer.valueOf(batchId),
+ "referenceTaxonId", IntegerType.INSTANCE, species.getReferenceTaxonId());
+ Preconditions.checkArgument(rowUpdated == 1, "Unable to update operation, to be linked with catch batch.");
+ }
+
+ public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
+ String speciesBatchId) {
+ List<SpeciesBatchFrequency> results = Lists.newArrayList();
+
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ if (catchBatchId == null) {
+ return results;
+ }
+
+ SortingBatch sortingBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
+
+ for (Iterator<Batch> iterator = sortingBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch source = (SortingBatch) iterator.next();
+ SpeciesBatchFrequency target = new SpeciesBatchFrequency();
+
+ entityToBean(source, target);
+ results.add(target);
+ }
+ return results;
+ }
+
+ protected void entityToBean(SortingBatch source, SpeciesBatchFrequency target) {
+
+ target.setId(source.getId().toString());
+
+ target.setNumber(source.getIndividualCount());
+ target.setWeight(source.getWeight());
+ target.setComment(source.getComments());
+
+ // Length step category
+ if (source.getSortingMeasurements().size() == 1) {
+ SortingMeasurement sm = source.getSortingMeasurements().iterator().next();
+ if (sm.getPmfm() != null && sm.getPmfm().getId() != null) {
+ Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(sm.getPmfm().getId());
+ target.setLengthStepCaracteristic(lengthStepCaracteristic);
+ }
+
+ // Length
+ target.setLengthStep(sm.getNumericalValue());
+ }
+ }
+
+ public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(
+ String speciesBatchId, List<SpeciesBatchFrequency> frequencies) {
+ Preconditions.checkNotNull(speciesBatchId);
+ Preconditions.checkNotNull(frequencies);
+
+ if (frequencies.size() == 0) {
+ return frequencies;
+ }
+ getCurrentSession().setFlushMode(FlushMode.COMMIT);
+
+ Integer catchBatchId = catchBatchDao.getIdBySortingBatchId(Integer.valueOf(speciesBatchId));
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.loadFullTree(catchBatchId);
+
+ if (catchBatch == null) {
+ return frequencies;
+ }
+
+ // Retrieve parent
+ SortingBatch parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(speciesBatchId));
+
+ // Remember child ids, to remove unchanged item (see at bottom in this method)
+ List<Integer> notUpdatedChildIds = Lists.newArrayList();
+ for (Iterator<Batch> iterator = parentBatch.getChildBatchs().iterator(); iterator.hasNext();) {
+ SortingBatch sortingBatch = (SortingBatch) iterator.next();
+ notUpdatedChildIds.add(sortingBatch.getId());
+ }
+
+ short rankOrder = 0;
+ String pmfmId = null;
+ List<SortingBatch> batchsToUpdate = Lists.newArrayList();
+ for (SpeciesBatchFrequency source : frequencies) {
+ rankOrder++;
+
+ // Check that all frequencies have the same length PMFM
+ if (pmfmId == null) {
+ source.getLengthStepCaracteristic().getId();
+ } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) {
+ throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic");
+ }
+
+ // Not existing batch
+ SortingBatch target = null;
+ if (source.getId() == null) {
+ target = SortingBatch.Factory.newInstance();
+
+ // Fill the sorting batch from the source
+ beanToEntity(source, target, parentBatch, rankOrder, true);
+
+ // Create the targeted batch, then update the source id
+ sortingBatchDao.create(target);
+ source.setId(target.getId().toString());
+ }
+
+ // Existing batch
+ else {
+ target = sortingBatchDao.load(Integer.valueOf(source.getId()));
+
+ // Fill the sorting batch from the source
+ beanToEntity(source, target, parentBatch, rankOrder, true);
+
+ // Add the batch into a list (will be update later, using this list)
+ batchsToUpdate.add(target);
+
+ notUpdatedChildIds.remove(target.getId());
+ }
+ }
+
+ // If some batchs need to be update, do it
+ if (batchsToUpdate.size() > 0) {
+ sortingBatchDao.update(batchsToUpdate);
+ }
+
+ if (notUpdatedChildIds.size() > 0) {
+ for (Iterator<Integer> iterator = notUpdatedChildIds.iterator(); iterator.hasNext();) {
+ Integer batchId = iterator.next();
+ catchBatchDao.removeWithChildren(batchId);
+ }
+ }
+
+ getCurrentSession().flush();
+
+ return frequencies;
+ }
+
+ // ------------------------------------------------------------------------//
+ // -- Internal methods --//
+ // ------------------------------------------------------------------------//
+
+ protected void validate(Collection<Batch> batchs, List<CatchBatchValidationError> errors, int treeLevel) {
+
+ List<Integer> expectedPmfms = null;
+ boolean expectedReferenceTaxon = false;
+ // First tree level : should have pmfm SORTED (Vrac, Hors Vrac, Non trié)
+ if (treeLevel == 1) {
+ expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+ // Second tree level : should have pmfm SORTING_TYPE (Species, Benthos...)
+ else if (treeLevel == 2) {
+ expectedPmfms = Lists.newArrayList(enumeration.PMFM_ID_SORTING_TYPE);
+ }
+ else if (treeLevel == 3) {
+ expectedReferenceTaxon = true;
+ }
+ else if (treeLevel > 3) {
+ expectedPmfms = referentialService.getSampleCategoryIds();
+ expectedPmfms.remove(enumeration.PMFM_ID_SORTED_UNSORTED);
+ }
+
+ // First level : should be only PMFM=SORTED
+ for (Iterator<Batch> iterator = batchs.iterator(); iterator.hasNext();) {
+ SortingBatch batch = (SortingBatch) iterator.next();
+ boolean batchHasError = false;
+
+ // For all sorting measurements
+ if (batch.getSortingMeasurements() != null && batch.getSortingMeasurements().size() > 0) {
+ for (Iterator<SortingMeasurement> iterator2 = batch.getSortingMeasurements().iterator(); iterator2.hasNext();) {
+ SortingMeasurement sm = iterator2.next();
+ Integer pmfmId = sm.getPmfm().getId();
+ if (expectedReferenceTaxon) {
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.onlyTaxonButPmfmFound",
+ _("tutti.persistence.batch.validation.onlyTaxonButPmfmFound", batch.getId(), pmfmId),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+ else if (expectedPmfms.contains(pmfmId) == false) {
+ if (sm.getNumericalValue() == null || batch.getChildBatchs().size() > 0) {
+ batchHasError = true;
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.pmfmNotFound",
+ _("tutti.persistence.batch.validation.pmfmNotFound",
+ batch.getId(), Arrays.toString(expectedPmfms.toArray()), pmfmId),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+ }
+ }
+ }
+ else if (expectedPmfms != null && expectedPmfms.size() > 0){
+ batchHasError = true;
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.pmfmNotFound",
+ _("tutti.persistence.batch.validation.pmfmNotFound",
+ batch.getId(), Arrays.toString(expectedPmfms.toArray()), "null"),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+
+ if (!batchHasError && expectedReferenceTaxon == true && batch.getReferenceTaxon() == null) {
+ CatchBatchValidationError error = new CatchBatchValidationError(
+ "tutti.persistence.batch.validation.referenceTaxonNotFound",
+ _("tutti.persistence.batch.validation.referenceTaxonNotFound", batch.getId()),
+ CatchBatchValidationError.GRAVITY_ERROR);
+ errors.add(error);
+ }
+
+ if (!batchHasError) {
+ validate(batch.getChildBatchs(), errors, treeLevel+1);
+ }
+ }
+ }
+
+ protected void beanToEntity(SpeciesBatch source,
+ SortingBatch target,
+ String parentBatchId,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch,
+ boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // If parent and root need to be set
+ if (target.getId() == null
+ || target.getRootBatch() == null
+ || (target.getParentBatch() != null && !target.getParentBatch().getId().toString().equals(parentBatchId))) {
+ setBatchParents(source, target, parentBatchId, catchBatch);
+ }
+
+ // RankOrder (initialize once, at creation)
+ if (target.getRankOrder() == null) {
+ // Start rank order at 3, because of special batches 'Biota' and 'Inert'
+ short rankOrder = (short) 3;
+ if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) {
+ // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?)
+ rankOrder += (short) source.getParentBatch().getChildBatchs().size();
+ }
+ target.setRankOrder(rankOrder);
+ }
+
+ // Force subgroup count to '1', as Allegro
+ target.setSubgroupCount(1f);
+
+ // Weight or SampleCategoryWeight
+ if (copyIfNull && source.getWeight() == null && source.getSampleCategoryWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getSampleCategoryWeight() != null && source.getWeight() == null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sampling Ratio
+ if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) {
+ String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight();
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight());
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sorting measurement
+ if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) {
+ Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
+ // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch)
+ if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
+ SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId,
+ source.getSampleCategoryType(), source.getSampleCategoryValue());
+ notChangedSortingMeasurements.remove(sortingMeasurement);
+ }
+ }
+
+ // Individual count
+ if (copyIfNull && source.getNumber() == null) {
+ target.setIndividualCount(null);
+ } else if (source.getNumber() != null) {
+ target.setIndividualCount(source.getNumber());
+ }
+
+ // Species
+ if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) {
+ target.setReferenceTaxon(null);
+ } else if (source.getSpecies() != null && parentBatchId == null) {
+ ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId());
+ target.setReferenceTaxon(referenceTaxon);
+ }
+
+ // QualityFlag
+ if (source.isSpeciesToConfirm()) {
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL));
+ } else {
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ }
+
+ // Comments
+ if (copyIfNull && source.getComment() == null) {
+ target.setComments(null);
+ } else if (source.getComment() != null) {
+ target.setComments(source.getComment());
+ }
+
+ // Exhaustive inventory (always true under a species batch)
+ target.setExhaustiveInventory(true);
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ public void setBatchParents(SpeciesBatch source, SortingBatch target, String parentBatchIdStr,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch) {
+
+ Preconditions.checkNotNull(target);
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Load existing parent and root
+ SortingBatch parentBatch = null;
+ if (parentBatchIdStr != null) {
+ parentBatch = catchBatchDao.getSortingBatchById(catchBatch, Integer.valueOf(parentBatchIdStr));
+ }
+
+ // Or retrieve parent batch, from pmfm id
+ else {
+ // Retrieve category type
+ Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
+ if (pmfmId == null || !pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
+ throw new DataIntegrityViolationException(MessageFormat.format(
+ "A species batch with no parent should have a sampleCategoryType {0} (PMFM.ID={1})",
+ SampleCategoryEnum.sortedUnsorted.name(),
+ enumeration.PMFM_ID_SORTED_UNSORTED));
+ }
+ Integer qualitativeValueId = convertSampleCategoryValueIntoQualitativeId(source.getSampleCategoryValue());
+
+ parentBatch = catchBatchDao.getSortingBatch(catchBatch.getChildBatchs(),
+ "pmfmId", pmfmId, qualitativeValueId,
+ "pmfmId", enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+
+ // Parent Batch
+ target.setParentBatch(parentBatch);
+ }
+
+
+ if (parentBatch == null) {
+ throw new DataIntegrityViolationException(
+ "Could not retrieve parent batch, for a given speciesBatch : invalid batch tree structure. Please make sure CatchBatch has been saved before to create a SpeciesBatch.");
+ }
+
+ // Parent Batch
+ target.setParentBatch(parentBatch);
+ target.setRootBatch(catchBatch);
+ }
+
+ Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) {
+ if (value == null)
+ return null;
+ Integer qualitativeValueId = null;
+ if (value instanceof CaracteristicQualitativeValue) {
+ CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value;
+ qualitativeValueId = Integer.valueOf(cqValue.getId());
+ } else if (value instanceof String) {
+ qualitativeValueId = Integer.valueOf((String) value);
+ }
+ return qualitativeValueId;
+ }
+
+ protected void setSampleCategoryQualitative(SpeciesBatch target, Integer pmfmId, Float numericalvalue, String alphanumericalValue,
+ Integer qualitativeValueId) {
+ // skip if null or corresponding to the SORTING_TYPE PMFM (Expèce, Benthos, Plancton, etc.)
+ if (pmfmId == null || pmfmId.equals(enumeration.PMFM_ID_SORTING_TYPE)) {
+ return;
+ }
+
+ SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
+ Preconditions.checkNotNull(sampleCategory, "Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId);
+
+ target.setSampleCategoryType(sampleCategory);
+ if (numericalvalue != null) {
+ target.setSampleCategoryValue(numericalvalue);
+ return;
+ }
+ if (alphanumericalValue != null) {
+ target.setSampleCategoryValue(alphanumericalValue);
+ return;
+ }
+
+ Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId);
+ if (caracteristic == null || caracteristic.getCaracteristicType() != CaracteristicType.QUALITATIVE) {
+ return;
+ }
+ CaracteristicQualitativeValue value = null;
+ for (CaracteristicQualitativeValue qv : caracteristic.getQualitativeValue()) {
+ if (qualitativeValueId == Integer.parseInt(qv.getId())) {
+ value = qv;
+ break;
+ }
+ }
+ target.setSampleCategoryValue(value);
+ }
+
+ protected void beanToEntity(SpeciesBatchFrequency source, SortingBatch target, SortingBatch parentBatch, short rankOrder, boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getBatch());
+ Preconditions.checkNotNull(source.getBatch().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // If parent and root need to be set
+ if (target.getId() == null
+ || target.getRootBatch() == null
+ || (target.getParentBatch() != null && !target.getParentBatch().getId().equals(parentBatch.getId()))) {
+
+ target.setParentBatch(parentBatch);
+ target.setRootBatch(parentBatch.getRootBatch());
+ }
+
+ // RankOrder
+ target.setRankOrder(rankOrder);
+
+ // Weight or SampleCategoryWeight
+ if (copyIfNull && source.getWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getWeight() != null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Sorting measurement
+ if (copyIfNull && (source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (source.getLengthStepCaracteristic() != null && source.getLengthStep() != null) {
+ Integer pmfmId = Integer.valueOf(source.getLengthStepCaracteristic().getId());
+ SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, pmfmId,
+ source.getLengthStep());
+ notChangedSortingMeasurements.remove(sortingMeasurement);
+ }
+
+ // Individual count
+ if (copyIfNull && source.getNumber() == null) {
+ target.setIndividualCount(null);
+ } else if (source.getNumber() != null) {
+ target.setIndividualCount(source.getNumber());
+ }
+
+ // Species
+ target.setReferenceTaxon(null);
+
+ // QualityFlag
+ target.setQualityFlag(parentBatch.getQualityFlag());
+
+ // Comments
+ if (copyIfNull && source.getComment() == null) {
+ target.setComments(null);
+ } else if (source.getComment() != null) {
+ target.setComments(source.getComment());
+ }
+
+ // Exhaustive inventory (always true under a species batch)
+ target.setExhaustiveInventory(true);
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected UIWeight convertDatabase2UI(Float weight, Float samplingRatio, String samplingRatioText) {
+ UIWeight result = new UIWeight();
+
+ // Weight & sampleCategory Weight
+ if (samplingRatio == null) {
+ result.sampleCategoryWeight = weight;
+ } else if (weight != null) {
+ String startStr = weight.toString().replace(',', '.') + "/";
+ if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
+ String weightStr = samplingRatioText.substring(startStr.length());
+ if (weightStr != null && !weightStr.isEmpty()) {
+ result.sampleCategoryWeight = Float.parseFloat(weightStr);
+ result.weight = weight;
+ }
+ } else {
+ result.sampleCategoryWeight = weight;
+ }
+ }
+ return result;
+ }
+
+ static class UIWeight {
+ Float sampleCategoryWeight = null;
+
+ Float weight = null;
+ }
+
+ protected void beanToEntity(CatchBatch source,
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch target,
+ boolean copyIfNull) {
+ Preconditions.checkNotNull(source.getFishingOperation());
+ Preconditions.checkNotNull(source.getFishingOperation().getId());
+
+ // Retrieve recorder department
+ Integer recorderDepartmentId = getRecorderDepartmentId();
+
+ // First initialization (when created)
+ Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId());
+ target.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId));
+
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRankOrder((short) 1);
+ target.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue());
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+
+ // Total Weight
+ if (copyIfNull && source.getCatchTotalWeight() == null) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (source.getCatchTotalWeight() != null) {
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getCatchTotalWeight(), true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ Map<Integer, SortingBatch> catchBatchChilds = getChildsMap(target, enumeration.PMFM_ID_SORTED_UNSORTED);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac
+ // -----------------------------------------------------------------------------
+ {
+ SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_VRAC_ID);
+ if (batch == null) {
+ batch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(batch);
+ }
+ beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
+ source.getCatchTotalSortedCarousselWeight(), source.getCatchTotalSortedTremisWeight(),
+ copyIfNull);
+ batch.setRankOrder((short) 1);
+
+ // Manage childs :
+ {
+ Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species
+ // -----------------------------------------------------------------------------
+ SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ if (speciesBatch == null) {
+ speciesBatch = SortingBatch.Factory.newInstance();
+ if (batch.getChildBatchs() == null) {
+ batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
+ } else {
+ batch.getChildBatchs().add(speciesBatch);
+ }
+ }
+ beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
+ source.getSpeciesTotalSampleSortedWeight(), source.getSpeciesTotalSortedWeight(),
+ copyIfNull);
+ speciesBatch.setRankOrder((short) 1);
+
+ {
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species / Alive not itemized
+ // -----------------------------------------------------------------------------
+ SortingBatch aliveNotItemizedBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_LIFE);
+ if (aliveNotItemizedBatch == null) {
+ aliveNotItemizedBatch = SortingBatch.Factory.newInstance();
+ if (speciesBatch.getChildBatchs() == null) {
+ speciesBatch.setChildBatchs(Lists.newArrayList((Batch) aliveNotItemizedBatch));
+ } else {
+ speciesBatch.getChildBatchs().add(aliveNotItemizedBatch);
+ }
+ }
+ beanToEntityReferenceTaxonBatch(target, speciesBatch, aliveNotItemizedBatch, recorderDepartmentId,
+ enumeration.REFERENCE_TAXON_ID_LIFE,
+ source.getSpeciesTotalLivingNotItemizedWeight(), null,
+ copyIfNull);
+ aliveNotItemizedBatch.setRankOrder((short) 1);
+
+ // -----------------------------------------------------------------------------
+ // Sorted Vrac / Species / Inert (not alive)
+ // -----------------------------------------------------------------------------
+ SortingBatch inertBatch = catchBatchDao.getSortingBatch(speciesBatch.getChildBatchs(), "referenceTaxonId", enumeration.REFERENCE_TAXON_ID_INERT);
+ if (inertBatch == null) {
+ inertBatch = SortingBatch.Factory.newInstance();
+ speciesBatch.getChildBatchs().add(inertBatch);
+ }
+ beanToEntityReferenceTaxonBatch(target, speciesBatch, inertBatch, recorderDepartmentId,
+ enumeration.REFERENCE_TAXON_ID_INERT,
+ source.getSpeciesTotalInertWeight(), null,
+ copyIfNull);
+ inertBatch.setRankOrder((short) 2);
+ }
+ }
+ // TODO BL : benthos, plancton, macro déchet...
+ }
+
+ // -----------------------------------------------------------------------------
+ // Sorted Hors Vrac
+ // -----------------------------------------------------------------------------
+ {
+ SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_HORS_VRAC_ID);
+ if (batch == null) {
+ batch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(batch);
+ }
+ beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
+ source.getCatchTotalUnsortedWeight(), null,
+ copyIfNull);
+ batch.setRankOrder((short) 2);
+
+ // Manage childs :
+ {
+ Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
+
+ // Species :
+ SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
+ if (speciesBatch == null) {
+ speciesBatch = SortingBatch.Factory.newInstance();
+ if (batch.getChildBatchs() == null) {
+ batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
+ } else {
+ batch.getChildBatchs().add(speciesBatch);
+ }
+ }
+ beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
+ source.getSpeciesTotalUnsortedWeight(), null,
+ copyIfNull);
+ speciesBatch.setRankOrder((short) 1);
+ }
+
+ // TODO BL : benthos, plancton, macro déchet...
+ }
+
+ // -----------------------------------------------------------------------------
+ // Unsorted (=rejected)
+ // -----------------------------------------------------------------------------
+ // Unsorted :
+ SortingBatch unsortedBatch = catchBatchChilds.get(enumeration.QUALITATIVE_UNSORTED_ID);
+ if (unsortedBatch == null) {
+ unsortedBatch = SortingBatch.Factory.newInstance();
+ target.getChildBatchs().add(unsortedBatch);
+ }
+ beanToEntitySortingBatch(target, target, unsortedBatch, recorderDepartmentId,
+ enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID,
+ source.getCatchTotalRejectedWeight(), null,
+ copyIfNull);
+ unsortedBatch.setRankOrder((short) 3);
+
+ }
+
+ protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) {
+ Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
+ if (parentBatch.getChildBatchs() == null) {
+ return batchByQualitativeValueId;
+ }
+ for (Batch childBatch : parentBatch.getChildBatchs()) {
+ SortingBatch childSortingBatch = (SortingBatch) childBatch;
+ SortingMeasurement sm = measurementHelper.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false);
+ if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) {
+ batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), childSortingBatch);
+ }
+ }
+ return batchByQualitativeValueId;
+ }
+
+ /**
+ * Retrieve child batchs if species is "Life" or "No life"
+ * (need to retrieve: speciesTotalLivingNotItemizedWeight and speciesTotalInertWeight)
+ *
+ * @param parentBatch
+ * @return
+ */
+ protected Map<Integer, SortingBatch> getChildAliveNotSortedOrInert(Batch parentBatch) {
+ Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
+ if (parentBatch.getChildBatchs() == null) {
+ return batchByQualitativeValueId;
+ }
+ for (Batch childBatch : parentBatch.getChildBatchs()) {
+ SortingBatch childSortingBatch = (SortingBatch) childBatch;
+ if (childSortingBatch.getReferenceTaxon() != null && childSortingBatch.getId().intValue() < 0) {
+ if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
+ batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
+ } else if (enumeration.REFERENCE_TAXON_ID_LIFE.equals(childSortingBatch.getId())) {
+ batchByQualitativeValueId.put(enumeration.REFERENCE_TAXON_ID_LIFE, childSortingBatch);
+ }
+ }
+ }
+ return batchByQualitativeValueId;
+ }
+
+ protected void beanToEntitySortingBatch(
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
+ fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
+ fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
+ Integer recorderDepartmentId,
+ Integer sortingPmfmId,
+ Integer sortingQualitativeValueId,
+ Float weight,
+ Float sampleWeight,
+ boolean copyIfNull) {
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // Some mandatory properties :
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRootBatch(rootBatch);
+ target.setParentBatch(parentBatch);
+ target.setExhaustiveInventory(true);
+
+ // No taxon or taxon group
+ target.setReferenceTaxon(null);
+ target.setTaxonGroup(null);
+
+ // Sorting measurement
+ if (copyIfNull && (sortingPmfmId == null || sortingQualitativeValueId == null)) {
+ // Nothing to do : will be removed later, using notChangedSortingMeasurements
+ } else if (sortingPmfmId != null && sortingQualitativeValueId != null) {
+ SortingMeasurement sm = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId);
+ notChangedSortingMeasurements.remove(sm);
+ }
+
+ // Sampling Ratio
+ if (copyIfNull && (sampleWeight == null || weight == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (sampleWeight != null && weight != null) {
+ String samplingRatioText = weight + "/" + sampleWeight;
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(weight / sampleWeight);
+ }
+
+ // Weight
+ if (copyIfNull && (sampleWeight == null && weight == null)) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (sampleWeight != null || weight != null) {
+ Float batchReferenceWeight = weight;
+ if (batchReferenceWeight == null) {
+ batchReferenceWeight = sampleWeight;
+ }
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected void beanToEntityReferenceTaxonBatch(
+ fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
+ fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
+ fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
+ Integer recorderDepartmentId,
+ Integer referenceTaxonId,
+ Float weight,
+ Float sampleWeight,
+ boolean copyIfNull) {
+
+ // Create lists to store all updates, then remove not updated items
+ Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
+ if (target.getQuantificationMeasurements() != null) {
+ notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
+ }
+ Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
+ if (target.getSortingMeasurements() != null) {
+ notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
+ }
+
+ // Some mandatory properties :
+ target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
+ target.setRootBatch(rootBatch);
+ target.setParentBatch(parentBatch);
+ target.setExhaustiveInventory(true);
+
+ // Reference taxon
+ target.setReferenceTaxon(load(ReferenceTaxonImpl.class, referenceTaxonId));
+ target.setTaxonGroup(null);
+
+ // Sampling Ratio
+ if (copyIfNull && (sampleWeight == null || weight == null)) {
+ target.setSamplingRatio(null);
+ target.setSamplingRatioText(null);
+ } else if (sampleWeight != null && weight != null) {
+ String samplingRatioText = weight + "/" + sampleWeight;
+ samplingRatioText = samplingRatioText.replaceAll(",", ".");
+ target.setSamplingRatioText(samplingRatioText);
+ target.setSamplingRatio(weight / sampleWeight);
+ }
+
+ // Weight
+ if (copyIfNull && (sampleWeight == null && weight == null)) {
+ // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
+ } else if (sampleWeight != null || weight != null) {
+ Float batchReferenceWeight = weight;
+ if (batchReferenceWeight == null) {
+ batchReferenceWeight = sampleWeight;
+ }
+ QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target,
+ enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
+ notChangedQuantificationMeasurements.remove(quantificationMeasurement);
+ }
+
+ // Removed not changed measurements (in sorting and quantification measurement lists)
+ if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
+ for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
+ target.getQuantificationMeasurements().remove(qm);
+ }
+ }
+ if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
+ for (SortingMeasurement sm : notChangedSortingMeasurements) {
+ target.getSortingMeasurements().remove(sm);
+ }
+ }
+ }
+
+ protected Integer getRecorderDepartmentId() {
+ // TODO BL : voir si on peut récupérer le departement (du 1er saisisseur ?)
+ return enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
+ }
+}
Deleted: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/CatchBatchPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -1,437 +0,0 @@
-package fr.ifremer.tutti.persistence.service;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import fr.ifremer.adagio.core.dao.data.batch.Batch;
-import fr.ifremer.adagio.core.dao.data.batch.CatchBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
-import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
-import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
-import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl;
-import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
-import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus;
-import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
-import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.FlushMode;
-import org.hibernate.type.IntegerType;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.DataRetrievalFailureException;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.Resource;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.0
- */
-@Service("catchBatchPersistenceService")
-public class CatchBatchPersistenceServiceImpl extends AbstractPersistenceService implements CatchBatchPersistenceService {
-
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(CatchBatchPersistenceServiceImpl.class);
-
- @Resource(name = "referentialPersistenceService")
- protected ReferentialPersistenceService referentialService;
-
- @Resource(name = "denormalizedBatchDao")
- protected DenormalizedBatchDao denormalizedBatchDao;
-
- @Resource(name = "sortingBatchDao")
- protected SortingBatchDao sortingBatchDao;
-
- @Resource(name = "catchBatchDao")
- protected CatchBatchDao catchBatchDao;
-
- @Resource(name = "measurementPersistenceHelper")
- protected MeasurementPersistenceHelper measurementHelper;
-
-
- @Override
- public CatchBatch getCatchBatchFromFishingOperation(String id) {
- Preconditions.checkNotNull(id);
-
- Iterator<Object[]> list = queryList("catchBatch",
- "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(id),
- "pmfmIdSorted", IntegerType.INSTANCE, enumeration.PMFM_ID_SORTED_UNSORTED,
- "pmfmIdSortingType", IntegerType.INSTANCE, enumeration.PMFM_ID_SORTING_TYPE);
-
- int rowCount = 0;
- CatchBatch result = new CatchBatch();
- Integer previousSortedBatchId = null;
- while (list.hasNext()) {
- Object[] source = list.next();
- rowCount++;
-
- if (rowCount == 1) {
- // Id
- result.setId(source[0].toString());
-
- // Total weight
- Float totalWeight = (Float) source[1];
- result.setCatchTotalWeight(totalWeight);
- }
-
- Integer sortedBatchId = (Integer) source[2];
- Integer sortedQualitativeValueId = (Integer) source[5];
- if (sortedBatchId != null && !sortedBatchId.equals(previousSortedBatchId)) {
- // TODO BL : retrieve QV
- String samplingRatioText = (String) source[3];
- Float weight = (Float) source[4];
- if (weight != null && enumeration.QUALITATIVE_VRAC_ID.equals(sortedQualitativeValueId)) {
- result.setCatchTotalSortedCarousselWeight(weight);
- result.setCatchTotalSortedTremisWeight(getTotalWeight(weight, samplingRatioText));
- } else if (weight != null && enumeration.QUALITATIVE_HORS_VRAC_ID.equals(sortedQualitativeValueId)) {
- result.setCatchTotalUnsortedWeight(weight);
- if (samplingRatioText != null && !samplingRatioText.isEmpty()) {
- // TODO BL : throw error because baths are not compatible with tutti ??
- }
- } else if (weight != null && enumeration.QUALITATIVE_UNSORTED_ID.equals(sortedQualitativeValueId)) {
- result.setCatchTotalRejectedWeight(weight);
- if (samplingRatioText != null && !samplingRatioText.isEmpty()) {
- // TODO BL : throw error because baths are not compatible with tutti ??
- }
- }
- }
-
- Integer sortingTypeBatchId = (Integer) source[6];
- {
- String samplingRatioText = (String) source[7];
- Float weight = (Float) source[8];
- Integer qualitativeValueId = (Integer) source[9];
- if (weight != null) {
- if (enumeration.QUALITATIVE_VRAC_ID.equals(sortedQualitativeValueId)
- && enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES.equals(qualitativeValueId)) {
- result.setSpeciesTotalSampleSortedWeight(weight);
- result.setSpeciesTotalSortedWeight(getTotalWeight(weight, samplingRatioText));
- } else if (enumeration.QUALITATIVE_HORS_VRAC_ID.equals(sortedQualitativeValueId)
- && enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES.equals(qualitativeValueId)) {
- result.setSpeciesTotalUnsortedWeight(weight);
- // TODO error si samplingRatio not null
- }
- // TOBO BL : add benthos, plancton, etc.
- }
- }
-
-
- previousSortedBatchId = sortedBatchId;
- }
-
- return result;
- }
-
- @Override
- public CatchBatch createCatchBatch(CatchBatch bean) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkArgument(bean.getId() == null);
- Preconditions.checkNotNull(bean.getFishingOperation());
- Preconditions.checkNotNull(bean.getFishingOperation().getId());
-
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = fr.ifremer.adagio.core.dao.data.batch.CatchBatch.Factory.newInstance();
- beanToEntity(bean, catchBatch, true);
- catchBatch = catchBatchDao.create(catchBatch);
- bean.setId(String.valueOf(catchBatch.getId()));
-
- // Link to fishing operation
- getCurrentSession().flush();
- Integer fishingOperationId = Integer.valueOf(bean.getFishingOperation().getId());
- int rowUpdated = queryUpdate("updateFishingOperationCatchBatch",
- "fishingOperationId", IntegerType.INSTANCE, fishingOperationId,
- "catchBatchId", IntegerType.INSTANCE, catchBatch.getId());
- if (rowUpdated == 0) {
- throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found.");
- }
-
- return bean;
- }
-
- @Override
- public CatchBatch saveCatchBatch(CatchBatch bean) {
-
- Preconditions.checkNotNull(bean);
- Preconditions.checkNotNull(bean.getId());
-
- getCurrentSession().enableFetchProfile("batch-with-childs");
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch catchBatch = catchBatchDao.load(Integer.valueOf(bean.getId()));
- if (catchBatch == null) {
- throw new DataRetrievalFailureException("Could not retrieve catch batch with id=" + bean.getId());
- }
-
- beanToEntity(bean, catchBatch, true);
- catchBatchDao.update(catchBatch);
- getCurrentSession().flush();
- return bean;
- }
-
- // ------------------------------------------------------------------------//
- // -- Internal methods --//
- // ------------------------------------------------------------------------//
- protected void beanToEntity(CatchBatch source,
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch target,
- boolean copyIfNull) {
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve recorder department
- // TODO BLA : prendre le service du 1er saisisseur sur l'OP ?
- Integer recorderDepartmentId = enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
-
- // First initialization (when created)
- Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId());
- target.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId));
-
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRankOrder((short) 1);
- target.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue());
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
-
- // Total Weight
- if (copyIfNull && source.getCatchTotalWeight() == null) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (source.getCatchTotalWeight() != null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getCatchTotalWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- Map<Integer, SortingBatch> catchBatchChilds = getChildsMap(target, enumeration.PMFM_ID_SORTED_UNSORTED);
-
- // -----------------------------------------------------------------------------
- // Sorted Vrac
- // -----------------------------------------------------------------------------
- {
- SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_VRAC_ID);
- if (batch == null) {
- batch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(batch);
- }
- beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_VRAC_ID,
- source.getCatchTotalSortedTremisWeight(), source.getCatchTotalSortedCarousselWeight(),
- copyIfNull);
- batch.setRankOrder((short) 1);
-
- // Manage childs :
- {
- Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
-
- // Species :
- SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- if (speciesBatch == null) {
- speciesBatch = SortingBatch.Factory.newInstance();
- if (batch.getChildBatchs() == null) {
- batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
- } else {
- batch.getChildBatchs().add(speciesBatch);
- }
- }
- beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
- source.getSpeciesTotalSortedWeight(), source.getSpeciesTotalSampleSortedWeight(),
- copyIfNull);
- speciesBatch.setRankOrder((short) 1);
- }
- // TODO BL : benthos, plancton, macro déchet...
- }
-
- // -----------------------------------------------------------------------------
- // Sorted Hors Vrac
- // -----------------------------------------------------------------------------
- {
- SortingBatch batch = catchBatchChilds.get(enumeration.QUALITATIVE_HORS_VRAC_ID);
- if (batch == null) {
- batch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(batch);
- }
- beanToEntitySortingBatch(target, target, batch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_HORS_VRAC_ID,
- source.getCatchTotalUnsortedWeight(), null,
- copyIfNull);
- batch.setRankOrder((short) 2);
-
- // Manage childs :
- {
- Map<Integer, SortingBatch> batchChilds = getChildsMap(batch, enumeration.PMFM_ID_SORTING_TYPE);
-
- // Species :
- SortingBatch speciesBatch = batchChilds.get(enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
- if (speciesBatch == null) {
- speciesBatch = SortingBatch.Factory.newInstance();
- if (batch.getChildBatchs() == null) {
- batch.setChildBatchs(Lists.newArrayList((Batch) speciesBatch));
- } else {
- batch.getChildBatchs().add(speciesBatch);
- }
- }
- beanToEntitySortingBatch(target, batch, speciesBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTING_TYPE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES,
- source.getSpeciesTotalUnsortedWeight(), null,
- copyIfNull);
- speciesBatch.setRankOrder((short) 1);
- }
-
- // TODO BL : benthos, plancton, macro déchet...
- }
-
- // -----------------------------------------------------------------------------
- // Unsorted (=rejected)
- // -----------------------------------------------------------------------------
- // Unsorted :
- SortingBatch unsortedBatch = catchBatchChilds.get(enumeration.QUALITATIVE_UNSORTED_ID);
- if (unsortedBatch == null) {
- unsortedBatch = SortingBatch.Factory.newInstance();
- target.getChildBatchs().add(unsortedBatch);
- }
- beanToEntitySortingBatch(target, target, unsortedBatch, recorderDepartmentId,
- enumeration.PMFM_ID_SORTED_UNSORTED, enumeration.QUALITATIVE_UNSORTED_ID,
- source.getCatchTotalRejectedWeight(), null,
- copyIfNull);
- unsortedBatch.setRankOrder((short) 3);
-
-
- }
-
- protected Map<Integer, SortingBatch> getChildsMap(Batch parentBatch, Integer pmfmId) {
- Map<Integer, SortingBatch> batchByQualitativeValueId = new HashMap<Integer, SortingBatch>();
- if (parentBatch.getChildBatchs() == null) {
- return batchByQualitativeValueId;
- }
- for (Batch childBatch : parentBatch.getChildBatchs()) {
- SortingMeasurement sm = measurementHelper.getSortingMeasurement((SortingBatch) childBatch, pmfmId, null, false);
- if (sm != null && sm.getQualitativeValue() != null && sm.getQualitativeValue().getId() != null) {
- batchByQualitativeValueId.put(sm.getQualitativeValue().getId(), (SortingBatch) childBatch);
- }
- }
- return batchByQualitativeValueId;
- }
-
- protected void beanToEntitySortingBatch(
- fr.ifremer.adagio.core.dao.data.batch.CatchBatch rootBatch,
- fr.ifremer.adagio.core.dao.data.batch.Batch parentBatch,
- fr.ifremer.adagio.core.dao.data.batch.SortingBatch target,
- Integer recorderDepartmentId,
- Integer sortingPmfmId,
- Integer sortingQualitativeValueId,
- Float weight,
- Float sampleWeight,
- boolean copyIfNull) {
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // Some mandatory properties :
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- target.setRootBatch(rootBatch);
- target.setParentBatch(parentBatch);
-
- // Sorting measurement
- if (copyIfNull && (sortingPmfmId == null || sortingQualitativeValueId == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (sortingPmfmId != null && sortingQualitativeValueId != null) {
- SortingMeasurement sm = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, sortingPmfmId, sortingQualitativeValueId);
- notChangedSortingMeasurements.remove(sm);
- }
-
- // Sampling Ratio
- if (copyIfNull && (sampleWeight == null || weight == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (sampleWeight != null && weight != null) {
- String samplingRatioText = sampleWeight + "/" + weight;
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(sampleWeight / weight);
- }
-
- // Weight
- if (copyIfNull && (sampleWeight == null && weight == null)) {
- // Nothing to do : will be removed later, using notChangedQuantificationMeasurements
- } else if (sampleWeight != null || weight != null) {
- Float batchReferenceWeight = sampleWeight;
- if (batchReferenceWeight == null) {
- batchReferenceWeight = weight;
- }
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, batchReferenceWeight, true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- protected Float getTotalWeight(Float weight, String samplingRatioText) {
- if (weight == null) {
- return null;
- }
- String startStr = weight.toString().replace(',', '.') + "/";
- if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
- String weightStr = samplingRatioText.substring(startStr.length());
- if (weightStr != null && !weightStr.isEmpty()) {
- return Float.parseFloat(weightStr);
- }
- }
- // TODO BL : attention au saise "1/2" qui ne seront pas pris (mais "1.0/2.0" oui)
- return null;
- }
-
-}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceService.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -188,7 +188,9 @@
Caracteristic getCaracteristic(Integer pmfmId);
boolean isSortedQualitativeValue(CaracteristicQualitativeValue value);
-
+
+ List<Integer> getSampleCategoryIds();
+
/**
* Import given temporary species.
*
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/ReferentialPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -815,6 +815,20 @@
}
/**
+ * Return list of protected pmfm for sample category
+ * (i.e. to check the validity of a existing batch tree)
+ *
+ * @return
+ */
+ public List<Integer> getSampleCategoryIds() {
+ return Lists.newArrayList(enumeration.PMFM_ID_SORTED_UNSORTED
+ , enumeration.PMFM_ID_SIZE_CATEGORY
+ , enumeration.PMFM_ID_MATURITY
+ , enumeration.PMFM_ID_SEX
+ , enumeration.PMFM_ID_AGE);
+ }
+
+ /**
* Return true if the pmfm should NOT be used for caracteristics lists
* (i.e. because used somewhere when storing some properties into the database)
*
Deleted: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -1,812 +0,0 @@
-package fr.ifremer.tutti.persistence.service;
-
-/*
- * #%L
- * Tutti :: Persistence API
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2012 - 2013 Ifremer
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import fr.ifremer.adagio.core.dao.data.batch.CatchBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.CatchBatchImpl;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatch;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao;
-import fr.ifremer.adagio.core.dao.data.batch.SortingBatchImpl;
-import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao;
-import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement;
-import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement;
-import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl;
-import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon;
-import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl;
-import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
-import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
-import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
-import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
-import fr.ifremer.tutti.persistence.entities.referential.Species;
-import fr.ifremer.tutti.persistence.service.measure.MeasurementPersistenceHelper;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.FlushMode;
-import org.hibernate.type.IntegerType;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.Resource;
-import java.io.Serializable;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.3
- */
-@Service("speciesBatchPersistenceService")
-public class SpeciesBatchPersistenceServiceImpl extends
- AbstractPersistenceService implements SpeciesBatchPersistenceService {
-
- /** Logger. */
- private static final Log log = LogFactory
- .getLog(SpeciesBatchPersistenceServiceImpl.class);
-
- @Resource(name = "referentialPersistenceService")
- protected ReferentialPersistenceService referentialService;
-
- @Resource(name = "denormalizedBatchDao")
- protected DenormalizedBatchDao denormalizedBatchDao;
-
- @Resource(name = "sortingBatchDao")
- protected SortingBatchDao sortingBatchDao;
-
- @Resource(name = "catchBatchDao")
- protected CatchBatchDao catchBatchDao;
-
- @Resource(name = "measurementPersistenceHelper")
- protected MeasurementPersistenceHelper measurementHelper;
-
- @Override
- public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) {
- Iterator<Object[]> list = queryList("allSpeciesBatch",
- "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(fishingOperationId));
-
- List<SpeciesBatch> result = new ArrayList<SpeciesBatch>();
- List<SpeciesBatch> rootBatchs = new ArrayList<SpeciesBatch>();
-
- Map<String, SpeciesBatch> batchMapById = new HashMap<String, SpeciesBatch>();
- //TODO BLA : uncomment if a property speciesBatch.speciesBatchFrequency exists
- //Map<String, List<SpeciesBatchFrequency>> batchFrequenciesMapByParentId = new HashMap<String, List<SpeciesBatchFrequency>>();
- Map<String, String> parentBatchMapById = new HashMap<String, String>();
- while (list.hasNext()) {
- Object[] source = list.next();
-
- Integer parentbatchId = (Integer) source[11];
-
- // If row is not a species batch, load as batch frequency
- if (couldBeASpeciesBatchFrequency(source)) {
- //TODO BLA : uncomment if a property speciesBatch.speciesBatchFrequency exists
- //loadSpeciesBatchFrequency(source, batchFrequenciesMapByParentId);
- } else {
- // In all case, load row as species batch
- SpeciesBatch speciesBatch = loadSpeciesBatch(source);
-
- // Add result into a maps
- batchMapById.put(speciesBatch.getId(), speciesBatch);
- if (parentbatchId != null) {
- parentBatchMapById.put(speciesBatch.getId(), parentbatchId.toString());
- }
- }
- }
-
- // Retrieve the parent links for all batchs
- for (SpeciesBatch speciesBatch : batchMapById.values()) {
- // If retrieve the parent from the parent map
- String parentbatchId = parentBatchMapById.get(speciesBatch.getId());
- if (parentbatchId != null) {
- SpeciesBatch parentSpeciesBatch = batchMapById.get(parentbatchId);
-
- // If found, link the batch with its parent :
- if (parentSpeciesBatch != null) {
- speciesBatch.setParentBatch(parentSpeciesBatch);
- if (parentSpeciesBatch.getChildBatchs() == null) {
- parentSpeciesBatch.setChildBatchs(Lists.newArrayList(speciesBatch));
- } else {
- parentSpeciesBatch.addChildBatchs(speciesBatch);
- }
- }
-
- // If no parent found, the batch should be a direct child of the catch batch
- else {
- rootBatchs.add(speciesBatch);
- }
-
- //TODO BLA : uncomment if a property speciesBatch.speciesBatchFrequency exists
- //List<SpeciesBatchFrequency> batchFrequencies = batchFrequenciesMapByParentId.get(speciesBatch.getId());
- //if (batchFrequencies != null) {
- // speciesBatch.setSpeciesBatchFrequency(batchFrequencies);
- //}
- }
- }
-
- // Apply inheritance, starting with the catch batch children
- applyInheritedProperties(rootBatchs, null, null, result);
-
- return result;
- }
-
- @Override
- public SpeciesBatch createSpeciesBatch(SpeciesBatch bean,
- String parentBatchId) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkArgument(bean.getId() == null);
- Preconditions.checkNotNull(bean.getSpecies());
- Preconditions.checkNotNull(bean.getSpecies().getId());
- Preconditions.checkNotNull(bean.getFishingOperation());
- Preconditions.checkNotNull(bean.getFishingOperation().getId());
- // TODO BLA uncomment this after v1.0 :
- //Preconditions.checkNotNull(bean.getCatchBatch());
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- SortingBatch batch = SortingBatch.Factory.newInstance();
- beanToEntity(bean, batch, parentBatchId, true);
- batch = sortingBatchDao.create(batch);
-
- bean.setId(String.valueOf(batch.getId()));
-
- getCurrentSession().flush();
-
- return bean;
- }
-
- @Override
- public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) {
- Preconditions.checkNotNull(bean);
- Preconditions.checkNotNull(bean.getId());
-
- // TODO BL : pourquoi un clear() ? => pas nécessaire.
- //getCurrentSession().clear();
-
- getCurrentSession().enableFetchProfile("batch-with-measurements");
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
- SortingBatch batch = sortingBatchDao.load(Integer.valueOf(bean.getId()));
- String parentBatchId = null;
- if (bean.getParentBatch() != null) {
- parentBatchId = bean.getParentBatch().getId();
- }
- beanToEntity(bean, batch, parentBatchId, true);
- sortingBatchDao.update(batch);
- getCurrentSession().flush();
- return bean;
- }
-
- @Override
- public void deleteSpeciesBatch(String id) {
- Preconditions.checkNotNull(id);
-
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
-
- List<SortingBatch> allChildrenBatchs = Lists.newArrayList();
- removeAllChildrenBatchs(Integer.valueOf(id), allChildrenBatchs);
-
- getCurrentSession().flush();
- }
-
- @Override
- public void deleteSpeciesSubBatch(String id) {
- deleteSpeciesBatch(id);
- }
-
- @Override
- public void changeSpeciesBatchSpecies(String batchId, Species species) {
- Preconditions.checkNotNull(batchId);
- Preconditions.checkNotNull(species);
- Preconditions.checkNotNull(species.getReferenceTaxonId());
-
- if (log.isDebugEnabled()) {
- log.debug("Changing species for batch id="+batchId);
- }
-
- int rowUpdated = queryUpdate("updateBatchSpecies",
- "batchId", IntegerType.INSTANCE, Integer.valueOf(batchId),
- "referenceTaxonId", IntegerType.INSTANCE, species.getReferenceTaxonId());
- }
-
- @Override
- public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(
- String speciesBatchId) {
- Iterator<Object[]> list = queryList("allSpeciesBatchFrequency",
- "parentBatchId", IntegerType.INSTANCE, Integer.valueOf(speciesBatchId));
-
- List<SpeciesBatchFrequency> results = Lists.newArrayList();
-
- while (list.hasNext()) {
- Object[] source = list.next();
- SpeciesBatchFrequency target = new SpeciesBatchFrequency();
-
- int colIndex = 0;
- target.setId(source[colIndex++].toString());
-
- target.setNumber((Integer) source[colIndex++]);
- target.setWeight((Float) source[colIndex++]);
- target.setComment((String) source[colIndex++]);
-
- // Length step category
- Integer lengthPmfmId = (Integer) source[colIndex++];
- Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(lengthPmfmId);
- target.setLengthStepCaracteristic(lengthStepCaracteristic);
-
- // Length
- target.setLengthStep((Float) source[colIndex++]);
- results.add(target);
- }
- return results;
- }
-
-
- @Override
- public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(
- String speciesBatchId, List<SpeciesBatchFrequency> frequencies) {
- Preconditions.checkNotNull(speciesBatchId);
- Preconditions.checkNotNull(frequencies);
-
- if (frequencies.size() == 0) {
- return frequencies;
- }
- getCurrentSession().setFlushMode(FlushMode.COMMIT);
- getCurrentSession().enableFetchProfile("batch-with-measurements");
-
- // Retirve parent
- SortingBatch parentBatch = sortingBatchDao.load(Integer.valueOf(speciesBatchId));
-
- short rankOrder = 0;
- String pmfmId = null;
- Map<SortingBatch, SpeciesBatchFrequency> batchsToCreate = Maps.newHashMap();
- List<SortingBatch> batchsToUpdate = Lists.newArrayList();
- for (SpeciesBatchFrequency source : frequencies) {
- rankOrder++;
-
- // Check that all frequencies have the same length PMFM
- if (pmfmId == null) {
- source.getLengthStepCaracteristic().getId();
- } else if (!pmfmId.equals(source.getLengthStepCaracteristic().getId())) {
- throw new DataIntegrityViolationException("Batch frequencies under one Speciesbatch must have all the same lengthStepCaracteristic");
- }
-
- // Not existing batch
- SortingBatch target = null;
- if (source.getId() == null) {
- target = SortingBatch.Factory.newInstance();
-
- // Fill the sorting batch from the source
- beanToEntity(source, target, parentBatch, rankOrder, true);
-
- // Create the targeted batch, then update the source id
- sortingBatchDao.create(target);
- source.setId(target.getId().toString());
- }
-
- // Existing batch
- else {
- target = sortingBatchDao.load(Integer.valueOf(source.getId()));
-
- // Fill the sorting batch from the source
- beanToEntity(source, target, parentBatch, rankOrder, true);
-
- // Add the batch into a list (will be update later, using this list)
- batchsToUpdate.add(target);
- }
- }
-
- // If some batchs need to be update, do it
- if (batchsToUpdate.size() > 0) {
- sortingBatchDao.update(batchsToUpdate);
- }
-
- getCurrentSession().flush();
-
- return frequencies;
- }
-
- // ------------------------------------------------------------------------//
- // -- Internal methods --//
- // ------------------------------------------------------------------------//
- protected void beanToEntity(SpeciesBatch source, SortingBatch target, String parentBatchId, boolean copyIfNull) {
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve recorder department
- // TODO BLA : prendre le service du 1er saisisseur ?
- Integer recorderDepartmentId = enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // If parent and root need to be set
- if (target.getId() == null
- || target.getRootBatch() == null
- || (target.getParentBatch() != null && !target.getParentBatch().getId().toString().equals(parentBatchId))) {
- setBatchParents(source, target, parentBatchId, notChangedSortingMeasurements);
- }
-
- // RankOrder
- if (target.getRankOrder() == null) {
- short rankOrder = (short) 1;
- if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) {
- // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?)
- rankOrder = (short) source.getParentBatch().getChildBatchs().size();
- }
- target.setRankOrder(rankOrder);
- }
-
- // Weight or SampleCategoryWeight
- if (copyIfNull && source.getWeight() == null && source.getSampleCategoryWeight() == null) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getSampleCategoryWeight() != null && source.getWeight() == null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- } else if (source.getWeight() != null && source.getSampleCategoryWeight() == null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sampling Ratio
- if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) {
- target.setSamplingRatio(null);
- target.setSamplingRatioText(null);
- } else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) {
- String samplingRatioText = source.getWeight() + "/" + source.getSampleCategoryWeight();
- samplingRatioText = samplingRatioText.replaceAll(",", ".");
- target.setSamplingRatioText(samplingRatioText);
- target.setSamplingRatio(source.getWeight() / source.getSampleCategoryWeight());
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sorting measurement
- if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) {
- Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
- // Do not store sorting measurement if pmfm = SORTED (already store in an ancestor batch)
- if (!pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
- SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, source.getSampleCategoryType(), source.getSampleCategoryValue());
- notChangedSortingMeasurements.remove(sortingMeasurement);
- }
- }
-
- // Individual count
- if (copyIfNull && source.getNumber() == null) {
- target.setIndividualCount(null);
- } else if (source.getNumber() != null) {
- target.setIndividualCount(source.getNumber());
- }
-
- // Species
- if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) {
- target.setReferenceTaxon(null);
- } else if (source.getSpecies() != null && parentBatchId == null) {
- ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, source.getSpecies().getReferenceTaxonId());
- target.setReferenceTaxon(referenceTaxon);
- }
-
- // QualityFlag
- if (source.isSpeciesToConfirm()) {
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL));
- } else {
- target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED));
- }
-
- // Comments
- if (copyIfNull && source.getComment() == null) {
- target.setComments(null);
- } else if (source.getComment() != null) {
- target.setComments(source.getComment());
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- public void setBatchParents(SpeciesBatch source, SortingBatch target, String parentBatchIdStr,
- Set<SortingMeasurement> notChangedSortingMeasurements) {
-
- Preconditions.checkNotNull(target);
- Preconditions.checkNotNull(source.getFishingOperation());
- Preconditions.checkNotNull(source.getFishingOperation().getId());
-
- // Retrieve parent and root batch
- if (parentBatchIdStr == null) {
- // Retrieve category type
- Integer pmfmId = measurementHelper.sampleCategory2PmfmId(source.getSampleCategoryType());
- if (pmfmId == null || !pmfmId.equals(enumeration.PMFM_ID_SORTED_UNSORTED)) {
- throw new DataIntegrityViolationException(MessageFormat.format("A species batch with no parent should have a sampleCategoryType {0} (PMFM.ID={1})",
- SampleCategoryEnum.sortedUnsorted.name(), enumeration.PMFM_ID_SORTED_UNSORTED));
- }
- Integer qualitativeValueId = convertSampleCategoryValueIntoQualitativeId(source.getSampleCategoryValue());
-
- Object[] cols = queryUnique("parentBatch",
- "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(source.getFishingOperation().getId()),
- "pmfmIdSorted", IntegerType.INSTANCE, enumeration.PMFM_ID_SORTED_UNSORTED,
- "qualitativeIdSorted", IntegerType.INSTANCE, qualitativeValueId,
- "pmfmIdSortingType", IntegerType.INSTANCE, enumeration.PMFM_ID_SORTING_TYPE,
- "qualitativeIdSortingType", IntegerType.INSTANCE, enumeration.QUALITATIVE_ID_SORTING_TYPE_SPECIES);
-
- if (cols == null) {
- throw new DataIntegrityViolationException("Catch batchs not presents, or invalid batch tree structure. Please make sure CatchBatch has been saved before to create a SpeciesBatch.");
- }
- // Parent Batch
- Integer parentBatchId = (Integer) cols[0];
- SortingBatch parentBatch = load(SortingBatchImpl.class, parentBatchId);
- target.setParentBatch(parentBatch);
-
- // Root Batch
- Integer rootBatchId = (Integer) cols[1];
- target.setRootBatch(load(CatchBatchImpl.class, rootBatchId));
- }
-
- // Load existing parent and root
- else {
- SortingBatch parentBatch = load(SortingBatchImpl.class, Integer.valueOf(parentBatchIdStr));
- target.setParentBatch(parentBatch);
- target.setRootBatch(parentBatch.getRootBatch());
- }
- }
-
- protected SpeciesBatch loadSpeciesBatch(Object[] source) {
- int colIndex = 0;
-
- SpeciesBatch result = new SpeciesBatch();
- result.setId(source[colIndex++].toString());
-
- // Individual count
- result.setNumber((Integer) source[colIndex++]);
-
- // Convert database weight (and sampling ratio) into UI weight and sampleCategoryWeight
- Float sourceWeight = (Float) source[colIndex++];
- Float sourceSamplingRatio = (Float) source[colIndex++];
- String sourceSamplingRatioText = (String) source[colIndex++];
- UIWeight uiWeight = convertDatabase2UI(sourceWeight, sourceSamplingRatio, sourceSamplingRatioText);
- result.setWeight(uiWeight.weight);
- result.setSampleCategoryWeight(uiWeight.sampleCategoryWeight);
-
- // Comments
- result.setComment((String) source[colIndex++]);
-
- // Sample category type
- Integer pmfmId = (Integer) source[colIndex++];
-
- // Sample category value
- Integer qvValue = (Integer) source[colIndex++];
- Float numValue = (Float) source[colIndex++];
- String alphaValue = (String) source[colIndex++];
- if (pmfmId != null) {
- setSampleCategoryQualitative(result, pmfmId, numValue, alphaValue, qvValue);
- }
-
- // Species
- Integer referenceTaxonId = (Integer) source[colIndex++];
- if (referenceTaxonId != null) {
- // TODO : add cache on getSpeciesByReferenceTaxonId
- Species species = referentialService.getSpeciesByReferenceTaxonId(referenceTaxonId);
- result.setSpecies(species);
- }
-
- return result;
- }
-
- protected void applyInheritedProperties(List<SpeciesBatch> speciesBatchs, CaracteristicQualitativeValue inheritedSortedUnsortedValue, Species inheritedSpecies, List<SpeciesBatch> results) {
- if (speciesBatchs == null || speciesBatchs.size() == 0) {
- return;
- }
- for (SpeciesBatch speciesBatch : speciesBatchs) {
- // If batch store a species (in the database)
- if (speciesBatch.getSpecies() != null) {
- // Remove the link to the parent (not need in UI)
- speciesBatch.setParentBatch(null);
- // Store into result list only if species has been set (=species root batch)
- results.add(speciesBatch);
- }
-
- // Apply sampleCategoryValue inheritance, if need
- if (inheritedSortedUnsortedValue != null && speciesBatch.getSampleCategoryType() == null) {
- speciesBatch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
- speciesBatch.setSampleCategoryValue(inheritedSortedUnsortedValue);
- }
-
- // Apply species inheritance, if need
- if (speciesBatch.getSpecies() == null && inheritedSpecies != null) {
- speciesBatch.setSpecies(inheritedSpecies);
- }
-
- // Compute the inheritance sorted/unsorted value for children
- if (speciesBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted) {
- inheritedSortedUnsortedValue = (CaracteristicQualitativeValue) speciesBatch.getSampleCategoryValue();
- } else {
- inheritedSortedUnsortedValue = null;
- }
-
- // Recursive call : propagate species and sorted/unsorted value
- applyInheritedProperties(speciesBatch.getChildBatchs(),
- inheritedSortedUnsortedValue,
- speciesBatch.getSpecies(),
- results);
- }
- }
-
- Integer convertSampleCategoryValueIntoQualitativeId(Serializable value) {
- if (value == null) return null;
- Integer qualitativeValueId = null;
- if (value instanceof CaracteristicQualitativeValue) {
- CaracteristicQualitativeValue cqValue = (CaracteristicQualitativeValue) value;
- qualitativeValueId = Integer.valueOf(cqValue.getId());
- } else if (value instanceof String) {
- qualitativeValueId = Integer.valueOf((String) value);
- }
- return qualitativeValueId;
- }
-
- protected void setSampleCategoryQualitative(SpeciesBatch target, Integer pmfmId, Float numericalvalue, String alphanumericalValue, Integer qualitativeValueId) {
- // skip if null or corresponding to the SORTING_TYPE PMFM (Expèce, Benthos, Plancton, etc.)
- if (pmfmId == null || pmfmId.equals(enumeration.PMFM_ID_SORTING_TYPE)) {
- return;
- }
-
- SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
- Preconditions.checkNotNull(sampleCategory, "Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId);
-
- target.setSampleCategoryType(sampleCategory);
- if (numericalvalue != null) {
- target.setSampleCategoryValue(numericalvalue);
- return;
- }
- if (alphanumericalValue != null) {
- target.setSampleCategoryValue(alphanumericalValue);
- return;
- }
-
- Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId);
- if (caracteristic == null || caracteristic.getCaracteristicType() != CaracteristicType.QUALITATIVE) {
- return;
- }
- CaracteristicQualitativeValue value = null;
- for (CaracteristicQualitativeValue qv : caracteristic.getQualitativeValue()) {
- if (qualitativeValueId == Integer.parseInt(qv.getId())) {
- value = qv;
- break;
- }
- }
- target.setSampleCategoryValue(value);
- }
-
- protected void removeAllChildrenBatchs(Integer batchId, List<SortingBatch> result) {
- Iterator<Integer> list = queryListTyped("speciesBatchChildren",
- "batchId", IntegerType.INSTANCE, batchId);
-
- // First, add childrens
- while (list.hasNext()) {
-
- removeAllChildrenBatchs(list.next(), result);
- }
-
- // Then add the given batch (after children, because of order need in "delete")
- SortingBatch batch = sortingBatchDao.load(batchId);
- //SortingBatch batch = (SortingBatch)getCurrentSession().get(SortingBatchImpl.class, batchId);
- batch.getSortingMeasurements().clear();
- batch.getQuantificationMeasurements().clear();
- sortingBatchDao.remove(batch);
- }
-
- protected void beanToEntity(SpeciesBatchFrequency source, SortingBatch target, SortingBatch parentBatch, short rankOrder, boolean copyIfNull) {
- Preconditions.checkNotNull(source.getBatch());
- Preconditions.checkNotNull(source.getBatch().getId());
-
- // Retrieve recorder department
- // TODO BLA : prendre le service du 1er saisisseur ?
- Integer recorderDepartmentId = enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT;
-
- // Create lists to store all updates, then remove not updated items
- Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>();
- if (target.getQuantificationMeasurements() != null) {
- notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements());
- }
- Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>();
- if (target.getSortingMeasurements() != null) {
- notChangedSortingMeasurements.addAll(target.getSortingMeasurements());
- }
-
- // If parent and root need to be set
- if (target.getId() == null
- || target.getRootBatch() == null
- || (target.getParentBatch() != null && !target.getParentBatch().getId().equals(parentBatch.getId()))) {
-
- target.setParentBatch(parentBatch);
- target.setRootBatch(parentBatch.getRootBatch());
- }
-
- // RankOrder
- target.setRankOrder(rankOrder);
-
- // Weight or SampleCategoryWeight
- if (copyIfNull && source.getWeight() == null) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getWeight() != null) {
- QuantificationMeasurement quantificationMeasurement = measurementHelper.setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true);
- notChangedQuantificationMeasurements.remove(quantificationMeasurement);
- }
-
- // Sorting measurement
- if (copyIfNull && (source.getLengthStepCaracteristic() == null || source.getLengthStep() == null)) {
- // Nothing to do : will be removed later, using notChangedSortingMeasurements
- } else if (source.getLengthStepCaracteristic() != null && source.getLengthStep() != null) {
- Integer pmfmId = Integer.valueOf(source.getLengthStepCaracteristic().getId());
- SortingMeasurement sortingMeasurement = measurementHelper.setSortingMeasurement(target, recorderDepartmentId, pmfmId, source.getLengthStep());
- notChangedSortingMeasurements.remove(sortingMeasurement);
- }
-
- // Individual count
- if (copyIfNull && source.getNumber() == null) {
- target.setIndividualCount(null);
- } else if (source.getNumber() != null) {
- target.setIndividualCount(source.getNumber());
- }
-
- // Species
- target.setReferenceTaxon(null);
-
- // QualityFlag
- target.setQualityFlag(parentBatch.getQualityFlag());
-
- // Comments
- if (copyIfNull && source.getComment() == null) {
- target.setComments(null);
- } else if (source.getComment() != null) {
- target.setComments(source.getComment());
- }
-
- // Removed not changed measurements (in sorting and quantification measurement lists)
- if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) {
- for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) {
- target.getQuantificationMeasurements().remove(qm);
- }
- }
- if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) {
- for (SortingMeasurement sm : notChangedSortingMeasurements) {
- target.getSortingMeasurements().remove(sm);
- }
- }
- }
-
- private SpeciesBatchFrequency loadSpeciesBatchFrequency(Object[] source, Map<String, List<SpeciesBatchFrequency>> batchFrequenciesMapByParentId) {
- SpeciesBatchFrequency target = new SpeciesBatchFrequency();
-
- int colIndex = 0;
- target.setId(source[colIndex++].toString());
-
- // Individual count
- target.setNumber((Integer) source[colIndex++]);
-
- // Covert database weight (and sampling ratio) into UI weight
- Float sourceWeight = (Float) source[colIndex++];
- Float sourceSamplingRatio = (Float) source[colIndex++];
- String sourceSamplingRatioText = (String) source[colIndex++];
- UIWeight uiWeight = convertDatabase2UI(sourceWeight, sourceSamplingRatio, sourceSamplingRatioText);
- target.setWeight(uiWeight.weight);
-
- target.setComment((String) source[colIndex++]);
-
- // Length step category
- Integer lengthPmfmId = (Integer) source[colIndex++];
- Caracteristic lengthStepCaracteristic = referentialService.getCaracteristic(lengthPmfmId);
- target.setLengthStepCaracteristic(lengthStepCaracteristic);
-
- // Qualitative value (should be null)
- Preconditions.checkState(source[colIndex++] == null, "Invalid batch tree format : batch frequency could not have a qualitative value.");
-
- // Length (skip qvValue and alphaValue column)
- target.setLengthStep((Float) source[colIndex++]);
-
- // Alphanumerical value (should be null)
- Preconditions.checkState(source[colIndex++] == null, "Invalid batch tree format : batch frequency could not have a alphanumerical value.");
-
- // Taxon (should be null)
- Preconditions.checkState(source[colIndex++] == null, "Invalid batch tree format : taxon frequency could not have species.");
-
- Integer parentBatchId = (Integer) source[colIndex++];
-
- // Add target into the result map
- List<SpeciesBatchFrequency> parentBatchFrequencies = batchFrequenciesMapByParentId.get(parentBatchId.toString());
- if (parentBatchFrequencies == null) {
- parentBatchFrequencies = Lists.newArrayList();
- batchFrequenciesMapByParentId.put(parentBatchId.toString(), parentBatchFrequencies);
- }
- parentBatchFrequencies.add(target);
-
- return target;
- }
-
- protected boolean couldBeASpeciesBatchFrequency(Object[] source) {
- Integer pmfmId = (Integer) source[6];
- Integer referenceTaxonId = (Integer) source[10];
- Float numericalValue = (Float) source[8];
- Integer parentbatchId = (Integer) source[11];
- SampleCategoryEnum sampleCategory = referentialService.getSampleCategoryByPmfmId(pmfmId);
-
- // Batch frequency is a batch with :
- // - a numerical value
- // - a parent
- // - no species
- // - no corresponding sample category
- return numericalValue != null && parentbatchId != null && referenceTaxonId == null && sampleCategory == null;
- }
-
- protected UIWeight convertDatabase2UI(Float weight, Float samplingRatio, String samplingRatioText) {
- UIWeight result = new UIWeight();
-
- // Weight & sampleCategory Weight
- if (samplingRatio == null) {
- result.sampleCategoryWeight = weight;
- } else if (weight != null) {
- String startStr = weight.toString().replace(',', '.') + "/";
- if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) {
- String weightStr = samplingRatioText.substring(startStr.length());
- if (weightStr != null && !weightStr.isEmpty()) {
- result.sampleCategoryWeight = Float.parseFloat(weightStr);
- result.weight = weight;
- }
- }
- else {
- result.sampleCategoryWeight = weight;
- }
- }
- return result;
- }
-
- static class UIWeight {
- Float sampleCategoryWeight = null;
-
- Float weight = null;
- }
-}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -188,6 +188,12 @@
@Value("${TaxonGroupTypeCode.COMMERCIAL_SPECIES}")
public final String TAXON_GROUP_TYPE_ID_COMMERCIAL_SPECIES = null;
+ @Value("${ReferenceTaxonId.LIFE}")
+ public final Integer REFERENCE_TAXON_ID_LIFE = null;
+
+ @Value("${ReferenceTaxonId.INERT}")
+ public final Integer REFERENCE_TAXON_ID_INERT = null;
+
public void init() {
Field[] declaredFields = getClass().getDeclaredFields();
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/TuttiPersistenceServiceLocator.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -80,13 +80,18 @@
FishingOperationPersistenceService.class);
}
+ public static BatchPersistenceService getBatchPersistenceService() {
+ return getPersistenceService("batchPersistenceService",
+ BatchPersistenceService.class);
+ }
+
public static CatchBatchPersistenceService getCatchBatchPersistenceService() {
- return getPersistenceService("catchBatchPersistenceService",
- CatchBatchPersistenceService.class);
+ return getPersistenceService("batchPersistenceService",
+ CatchBatchPersistenceService.class);
}
public static SpeciesBatchPersistenceService getSpeciesBatchPersistenceService() {
- return getPersistenceService("speciesBatchPersistenceService",
+ return getPersistenceService("batchPersistenceService",
SpeciesBatchPersistenceService.class);
}
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/measure/MeasurementPersistenceHelper.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/measure/MeasurementPersistenceHelper.java 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/measure/MeasurementPersistenceHelper.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -206,6 +206,19 @@
return sortingMeasurement;
}
+
+ public SortingMeasurement getInheritedSortingMeasurement(
+ SortingBatch sortingBatch, Integer pmfmId) {
+ if (sortingBatch.getInheritedSortingMeasurements() != null) {
+ for (SortingMeasurement qm : sortingBatch
+ .getInheritedSortingMeasurements()) {
+ if (pmfmId.equals(qm.getPmfm().getId())) {
+ return qm;
+ }
+ }
+ }
+ return null;
+ }
public Integer sampleCategory2PmfmId(SampleCategoryEnum sampleCategory) {
Integer pmfmId = null;
Modified: trunk/tutti-persistence/src/main/resources/applicationContext-service-tutti.xml
===================================================================
--- trunk/tutti-persistence/src/main/resources/applicationContext-service-tutti.xml 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/applicationContext-service-tutti.xml 2013-02-14 15:27:16 UTC (rev 413)
@@ -53,8 +53,8 @@
<property name="diskExpiryThreadIntervalSeconds" value="300"/>
</bean>
- <bean id="tuttiPmfmsCache" parent="tuttiAbstractEternalCache">
- <property name="cacheName" value="pmfms" />
+ <bean id="tuttiBatchTreeCache" parent="tuttiAbstractCache">
+ <property name="cacheName" value="batchTree" />
</bean>
<!-- Eternal caches : -->
@@ -67,6 +67,10 @@
<property name="timeToIdle" value="0"/>
</bean>
+ <bean id="tuttiPmfmsCache" parent="tuttiAbstractEternalCache">
+ <property name="cacheName" value="pmfms" />
+ </bean>
+
<bean id="tuttiFishingVesselsCache" parent="tuttiAbstractEternalCache">
<property name="cacheName" value="fishingVessels" />
</bean>
Modified: trunk/tutti-persistence/src/main/resources/i18n/tutti-persistence_fr_FR.properties
===================================================================
--- trunk/tutti-persistence/src/main/resources/i18n/tutti-persistence_fr_FR.properties 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/i18n/tutti-persistence_fr_FR.properties 2013-02-14 15:27:16 UTC (rev 413)
@@ -12,4 +12,7 @@
tutti.option.persistence.jdbc.url.description=URL de connexion à la base de données
tutti.option.persistence.jdbc.username.description=Login de l'utilisateur pour se connecter à la base de données
tutti.option.persistence.protocol.directory.description=Répertoire où sont conservés les protocoles
+tutti.persistence.batch.validation.onlyTaxonButPmfmFound=Batch [id\=%s] should not have any sorting measurement (should only have a reference taxon), but found pmfm [id\=%s].
+tutti.persistence.batch.validation.pmfmNotFound=Batch [id\=%s] should have a sorting measurement with a pmfm id in %s or a length pmfm, but found pmfm [id\=%s].
+tutti.persistence.batch.validation.referenceTaxonNotFound=Batch [id\=%s] should have a reference taxon.
tutti.persistence.config=Configuration de la persistence de Tutti
Modified: trunk/tutti-persistence/src/main/resources/queries-override.hbm.xml
===================================================================
--- trunk/tutti-persistence/src/main/resources/queries-override.hbm.xml 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/queries-override.hbm.xml 2013-02-14 15:27:16 UTC (rev 413)
@@ -310,77 +310,6 @@
<query-param name="pmfmIdSortingType" type="java.lang.Integer"/>
</query>
- <query name="allSpeciesBatch">
- <![CDATA[
- SELECT
- b.id as batchId,
- b.individualCount AS individualCount,
- qm.numericalValue AS weight,
- b.samplingRatio AS samplingRatio,
- b.samplingRatioText AS samplingRatioText,
- b.comments AS comments,
- sm.pmfm.id AS pmfmId,
- sm.qualitativeValue.id as qvValue,
- sm.numericalValue AS numValue,
- sm.alphanumericalValue AS alphaValue,
- b.referenceTaxon.id as referenceTaxonId,
- b.parentBatch.id as parentBatchId
- FROM
- SortingBatchImpl b
- INNER JOIN b.rootBatch cb
- LEFT OUTER JOIN b.sortingMeasurements sm
- LEFT OUTER JOIN b.quantificationMeasurements qm
- WHERE
- cb.fishingOperation.id=:fishingOperationId
- AND (
- qm is null
- OR qm.isReferenceQuantification=true
- )
- ORDER BY b.id
- ]]>
- <query-param name="fishingOperationId" type="java.lang.Integer"/>
- </query>
-
- <query name="parentBatch">
- <![CDATA[
- SELECT
- b2.id as parentBatchId,
- cb.id as rootBatchId
- FROM
- CatchBatchImpl cb
- INNER JOIN cb.childBatchs b1
- INNER JOIN b1.childBatchs b2,
- SortingMeasurementImpl sm1,
- SortingMeasurementImpl sm2
- WHERE
- cb.fishingOperation.id = :fishingOperationId
- AND sm1.sortingBatch.id=b1.id
- AND sm1.pmfm.id=:pmfmIdSorted
- AND sm1.qualitativeValue.id=:qualitativeIdSorted
- AND sm2.sortingBatch.id=b2.id
- AND sm2.pmfm.id=:pmfmIdSortingType
- AND sm2.qualitativeValue.id=:qualitativeIdSortingType
- ]]>
- <query-param name="fishingOperationId" type="java.lang.Integer"/>
- <query-param name="pmfmIdSorted" type="java.lang.Integer"/>
- <query-param name="qualitativeIdSorted" type="java.lang.Integer"/>
- <query-param name="pmfmIdSortingType" type="java.lang.Integer"/>
- <query-param name="qualitativeIdSortingType" type="java.lang.Integer"/>
- </query>
-
- <query name="speciesBatchChildren">
- <![CDATA[
- SELECT
- cb.id
- FROM
- SortingBatchImpl b
- INNER JOIN b.childBatchs cb
- WHERE
- b.id = :batchId
- ]]>
- <query-param name="batchId" type="java.lang.Integer"/>
- </query>
-
<query name="updateBatchSpecies">
<![CDATA[
UPDATE SortingBatchImpl b
@@ -815,16 +744,6 @@
<!--<fetch-profile name="tutti">-->
<!--TODO Create fetch profile to avoid eager loading -->
<!--</fetch-profile>-->
-
- <fetch-profile name="batch-with-measurements">
- <fetch entity="BatchImpl" association="quantificationMeasurements" style="join"/>
- <fetch entity="CatchBatchImpl" association="quantificationMeasurements" style="join"/>
- <fetch entity="SortingBatchImpl" association="sortingMeasurements" style="join"/>
- <fetch entity="SortingBatchImpl" association="quantificationMeasurements" style="join"/>
- </fetch-profile>
- <fetch-profile name="batch-with-childs">
- <fetch entity="BatchImpl" association="childBatchs" style="join"/>
- </fetch-profile>
-
+
</hibernate-mapping>
Modified: trunk/tutti-persistence/src/main/resources/tutti-db-conf.properties
===================================================================
--- trunk/tutti-persistence/src/main/resources/tutti-db-conf.properties 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/tutti-db-conf.properties 2013-02-14 15:27:16 UTC (rev 413)
@@ -46,4 +46,6 @@
hibernate.generate_statistics=false
hibernate.query.substitutions=true 1, false 0
hibernate.hbm2ddl.auto=none
-hibernate.default_batch_fetch_size=1
\ No newline at end of file
+hibernate.default_batch_fetch_size=1
+adagio.cache.use_tree_cache=true
+ehcache.disk.store.dir=c:/temp/ehcache
\ No newline at end of file
Modified: trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties
===================================================================
--- trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties 2013-02-14 10:40:25 UTC (rev 412)
+++ trunk/tutti-persistence/src/main/resources/tutti-db-enumerations.properties 2013-02-14 15:27:16 UTC (rev 413)
@@ -375,4 +375,10 @@
DepartmentId.UNKNOWN_RECORDER_DEPARTMENT=181
#TODO A creer (dans les enumerations Allegro)
-ProgramCode.SCIENTIFIC_CRUISE_PREFIX=CAM-
\ No newline at end of file
+ProgramCode.SCIENTIFIC_CRUISE_PREFIX=CAM-
+
+#Reference taxon correspondant à "Biota" (ou "Vie")
+ReferenceTaxonId.LIFE=7637
+#Reference taxon correspondant à "Non Biota" (ou "Non Vie" - matière inerte)
+# TODO : a creer dans la base harmonie et a�changer !
+ReferenceTaxonId.INERT=1
\ No newline at end of file
Added: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java (rev 0)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceReadTest.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -0,0 +1,187 @@
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id: CatchBatchPersistenceServiceReadTest.java 379 2013-02-10 13:41:29Z tchemit $
+ * $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/test/j… $
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.Cruise;
+import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.springframework.dao.DataRetrievalFailureException;
+
+import com.google.common.collect.Maps;
+
+/**
+ * To test {@link CatchBatchPersistenceService} for read operation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class BatchPersistenceServiceReadTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.readDb();
+
+ protected BatchPersistenceService service;
+ protected FishingOperationPersistenceService fishingOperationService;
+ protected FishingOperation fishingOperation;
+
+ @Before
+ public void setUp() throws Exception {
+ service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
+ fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
+
+ List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
+ assertNotNull(fishingOperations);
+ assertTrue(fishingOperations.size() > 0);
+ fishingOperation = fishingOperations.get(0);
+ assertNotNull(fishingOperation);
+ assertNotNull(fishingOperation.getId());
+ }
+
+ @Test
+ public void getCatchBatchFromFishingOperation() throws Exception {
+
+ try {
+ CatchBatch catchBatch = service.getCatchBatchFromFishingOperation(fishingOperation.getId());
+ fail("batch tree must be invalid (old CGFS tree structure), for fishing operation id=" + fishingOperation.getId());
+ }
+ catch(DataRetrievalFailureException drfe) {
+ // success
+ }
+ }
+
+ @Test
+ public void getAllRootSpeciesBatch(/*String fishingOperationId*/) {
+ }
+
+ @Test
+ public void getAllSpeciesBatchFrequency(/*String speciesBatchId*/) {
+
+ }
+
+ public static void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
+ assertNotNull(actualBatch);
+ assertNotNull(actualBatch.getId());
+ if (assertIdEquals && expectedBatch.getId() != null) {
+ assertEquals(expectedBatch.getId(), actualBatch.getId());
+ }
+ assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
+ assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
+ if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
+ assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
+ actualBatch.getSampleCategoryValue());
+ assertEquals(
+ ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
+ ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
+ } else {
+ assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
+ }
+ assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
+ assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
+ assertEquals(expectedBatch.getComment(), actualBatch.getComment());
+
+ // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
+ // (Because getSpeciesBatch(id) could not always retrieve the species)
+ if (expectedBatch.getSpecies() != null && (
+ expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
+ || actualBatch.getSpecies() != null)) {
+ assertNotNull(actualBatch.getSpecies());
+ assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
+ }
+ }
+
+ public static void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
+ assertNotNull(actualFrequencies);
+ assertEquals(expectedFrequencies.size(), actualFrequencies.size());
+
+ // Store actual batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
+ expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ }
+
+ // Store expected batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
+ assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
+ actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ assertNotNull(speciesBatchFrequency.getId());
+ }
+
+ for (Float lengthStep : expectedLengthMap.keySet()) {
+ SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
+ SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
+ if (assertIdEquals) {
+ assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
+ }
+ assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
+ assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
+ assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
+ assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
+ assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
+ //assertNotNull(expectedBatchFrequency.getBatch());
+ //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
+ }
+ }
+
+ public static SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
+ return getSpeciesBatch(speciesBatchId, TuttiPersistenceServiceLocator.getBatchPersistenceService().getAllRootSpeciesBatch(fishingOperationId));
+ }
+
+ public static SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
+ if (speciesBatchs == null) {
+ return null;
+ }
+ for (SpeciesBatch speciesBatch : speciesBatchs) {
+ if (speciesBatchId.equals(speciesBatch.getId())) {
+ return speciesBatch;
+ }
+ if (speciesBatch.getChildBatchs() != null) {
+ speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
+ if (speciesBatch != null) {
+ return speciesBatch;
+ }
+ }
+ }
+ return null;
+ }
+
+}
Added: trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java
===================================================================
--- trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java (rev 0)
+++ trunk/tutti-persistence/src/test/java/fr/ifremer/tutti/persistence/service/BatchPersistenceServiceWriteTest.java 2013-02-14 15:27:16 UTC (rev 413)
@@ -0,0 +1,621 @@
+package fr.ifremer.tutti.persistence.service;
+
+/*
+ * #%L
+ * Tutti :: Persistence API
+ * $Id: CatchBatchPersistenceServiceWriteTest.java 379 2013-02-10 13:41:29Z tchemit $
+ * $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/test/j… $
+ * %%
+ * Copyright (C) 2012 - 2013 Ifremer
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import fr.ifremer.tutti.persistence.DatabaseResource;
+import fr.ifremer.tutti.persistence.entities.data.CatchBatch;
+import fr.ifremer.tutti.persistence.entities.data.Cruise;
+import fr.ifremer.tutti.persistence.entities.data.FishingOperation;
+import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch;
+import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency;
+import fr.ifremer.tutti.persistence.entities.referential.Caracteristic;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicQualitativeValue;
+import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType;
+import fr.ifremer.tutti.persistence.entities.referential.Species;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.springframework.dao.DataRetrievalFailureException;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.*;
+
+/**
+ * To test {@link CatchBatchPersistenceService} for write operation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class BatchPersistenceServiceWriteTest {
+
+ @ClassRule
+ public static final DatabaseResource dbResource = DatabaseResource.writeDb();
+
+ protected BatchPersistenceService service;
+
+ protected CruisePersistenceService cruiseService;
+
+ protected FishingOperationPersistenceService fishingOperationService;
+
+ protected CatchBatchPersistenceService catchBatchService;
+
+ protected ReferentialPersistenceService referentialService;
+
+ protected Cruise cruise;
+
+ protected FishingOperation fishingOperationNoCatchBatch;
+
+ protected FishingOperation fishingOperationWithEmptyBatch;
+
+ protected CatchBatch catchBacth;
+
+ protected List<Species> species;
+
+ protected Caracteristic sortedUnsortedPMFM;
+
+ protected CaracteristicQualitativeValue horsVracQualitativeValue;
+
+ protected CaracteristicQualitativeValue vracQualitativeValue;
+
+ protected Caracteristic maturityPMFM;
+
+ protected CaracteristicQualitativeValue firstMaturityQualitativeValue;
+
+ protected Caracteristic sexPMFM;
+
+ protected CaracteristicQualitativeValue maleQualitativeValue;
+
+ protected CaracteristicQualitativeValue femaleQualitativeValue;
+
+ protected CaracteristicQualitativeValue unkQualitativeValue;
+
+ protected Caracteristic frequencyPMFM;
+
+ @Before
+ public void setUp() throws Exception {
+ service = TuttiPersistenceServiceLocator.getBatchPersistenceService();
+ cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService();
+ fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService();
+ catchBatchService = TuttiPersistenceServiceLocator.getCatchBatchPersistenceService();
+ referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService();
+
+ species = referentialService.getAllSpecies();
+ assertNotNull(species);
+ assertTrue(species.size() > 2);
+
+ cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId());
+ cruise.setId(null);
+ Calendar calendar = new GregorianCalendar();
+ cruise.setBeginDate(calendar.getTime());
+ cruise.setYear(calendar.get(Calendar.YEAR));
+ calendar.add(Calendar.MONTH, 1); // add one month
+ cruise.setEndDate(calendar.getTime());
+ cruise = cruiseService.createCruise(cruise);
+
+ // Create a first operation, with no cacth batch : to test CatchBatch insert/update :
+ List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId());
+ assertNotNull(fishingOperations);
+ assertTrue(fishingOperations.size() > 0);
+ fishingOperationNoCatchBatch = fishingOperations.get(0);
+ fishingOperationNoCatchBatch = fishingOperationService.getFishingOperation(fishingOperationNoCatchBatch.getId());
+ fishingOperationNoCatchBatch.setId(null);
+ fishingOperationNoCatchBatch.setCruise(cruise);
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 1);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationNoCatchBatch.setGearShootingStartDate(calendar.getTime());
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 10);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationNoCatchBatch.setGearShootingEndDate(calendar.getTime());
+ fishingOperationNoCatchBatch = fishingOperationService.createFishingOperation(fishingOperationNoCatchBatch);
+
+ // Create a second operation, with no cacth batch : to test CatchBatch insert/update :
+ fishingOperationWithEmptyBatch = fishingOperations.get(1);
+ fishingOperationWithEmptyBatch = fishingOperationService.getFishingOperation(fishingOperationWithEmptyBatch.getId());
+ fishingOperationWithEmptyBatch.setId(null);
+ fishingOperationWithEmptyBatch.setCruise(cruise);
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 11);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationWithEmptyBatch.setGearShootingStartDate(calendar.getTime());
+ calendar.setTime(new Date());
+ calendar.set(Calendar.HOUR_OF_DAY, 12);
+ calendar.set(Calendar.MILLISECOND, 0);
+ fishingOperationWithEmptyBatch.setGearShootingEndDate(calendar.getTime());
+ fishingOperationWithEmptyBatch = fishingOperationService.createFishingOperation(fishingOperationWithEmptyBatch);
+
+ catchBacth = new CatchBatch();
+ catchBacth.setFishingOperation(fishingOperationWithEmptyBatch);
+ catchBacth = catchBatchService.createCatchBatch(catchBacth);
+
+ sortedUnsortedPMFM = referentialService.getSortedUnsortedCaracteristic();
+ horsVracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(0);
+ vracQualitativeValue = sortedUnsortedPMFM.getQualitativeValue(1);
+ maturityPMFM = referentialService.getMaturityCaracteristic();
+ firstMaturityQualitativeValue = maturityPMFM.getQualitativeValue(0);
+ sexPMFM = referentialService.getSexCaracteristic();
+ maleQualitativeValue = sexPMFM.getQualitativeValue(1);
+ femaleQualitativeValue = sexPMFM.getQualitativeValue(2);
+ unkQualitativeValue = sexPMFM.getQualitativeValue(3);
+
+ List<Caracteristic> cara = referentialService.getAllCaracteristic();
+ for (Caracteristic caracteristic : cara) {
+ if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER
+ && caracteristic.getPrecision() != null
+ && caracteristic.getPrecision() == 0.5f) {
+ frequencyPMFM = caracteristic;
+ break;
+ }
+ }
+ assertNotNull("no numerical PMFM with a precision has been found. Could not define a PMFM for batch frequencies.", frequencyPMFM);
+
+ }
+
+ @Test
+ public void createAndSaveCatchBatch() throws Exception {
+ CatchBatch catchBatch;
+
+ catchBatch = new CatchBatch();
+ catchBatch.setFishingOperation(fishingOperationNoCatchBatch);
+
+ // -----------------------------------------------------------------------------
+ // 1. Test with only mandatory properties
+ // -----------------------------------------------------------------------------
+
+ // Create and reload (test round trip)
+ assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 2. Test with all properties
+ // -----------------------------------------------------------------------------
+ catchBatch.setId(null);
+ // total weight : 100kg
+ catchBatch.setCatchTotalWeight(75f);
+ // Vrac :
+ {
+ // note : poids trie par la balance tremis (thalassa) (init par pupitri)
+ catchBatch.setCatchTotalSortedTremisWeight(50f);
+ // note : poids vrac caroussel (thalassa) (init par pupitri) (vrac trie) ou bien "poids trié fournie par la table de tri (Sum(Si)
+ catchBatch.setCatchTotalSortedCarousselWeight(45f);
+
+ // Species
+ {
+ catchBatch.setSpeciesTotalSortedWeight(12f);
+ catchBatch.setSpeciesTotalSampleSortedWeight(8f);
+ catchBatch.setSpeciesTotalLivingNotItemizedWeight(0.2f);
+ catchBatch.setSpeciesTotalInertWeight(0.1f);
+ }
+ }
+ // Hors Vrac : 10kg
+ {
+ catchBatch.setCatchTotalUnsortedWeight(10f);
+
+ // Species
+ {
+ catchBatch.setSpeciesTotalUnsortedWeight(10f);
+ }
+ }
+ // Rejet : 15kg
+ catchBatch.setCatchTotalRejectedWeight(15f);
+
+ // Create and reload (test round trip)
+ assertCreateAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 2. Test save after modification
+ // -----------------------------------------------------------------------------
+ catchBatch.setCatchTotalSortedTremisWeight(null);
+ catchBatch.setCatchTotalSortedCarousselWeight(null);
+ catchBatch.setSpeciesTotalSortedWeight(null);
+ catchBatch.setSpeciesTotalSampleSortedWeight(null);
+ catchBatch.setCatchTotalUnsortedWeight(null);
+ catchBatch.setSpeciesTotalUnsortedWeight(null);
+
+ assertSaveAndReloadCatchBatch(catchBatch, fishingOperationNoCatchBatch.getId());
+ }
+
+ @Test
+ public void createAndSaveSpeciesBatchAndFrequencies() {
+ SpeciesBatch esp1Batch = null;
+ SpeciesBatch esp2Batch = null;
+ SpeciesBatch frequenciesParentBatch = null;
+ SpeciesBatch batch = null;
+ Species taxon1 = species.get(0);
+ Species taxon2 = species.get(1);
+
+ // -----------------------------------------------------------------------------
+ // 1. Test with only mandatory properties
+ // -----------------------------------------------------------------------------
+ // batch : "ESP1 - Vrac/5"
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setFishingOperation(fishingOperationNoCatchBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(5f);
+
+ assertCreateAndReloadSpeciesBatch(batch, null);
+
+ // Save ESP1 batch
+ esp1Batch = batch;
+
+ // -----------------------------------------------------------------------------
+ // 2. Test child "Male/2"
+ // -----------------------------------------------------------------------------
+ // Batch : ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp1Batch);
+ batch.setSpecies(taxon1);
+ batch.setComment("ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(maleQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ batch.setWeight(1f);
+ batch.setNumber(7);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 3. Test child "Female/2"
+ // -----------------------------------------------------------------------------
+ // Batch : ESP1 - Vrac/5 Female/3 Nombre/14
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp1Batch);
+ batch.setSpecies(taxon1);
+ batch.setComment("ESP1 - Vrac/5 Female/3 Nombre/14");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(femaleQualitativeValue);
+ batch.setSampleCategoryWeight(3f);
+ batch.setWeight(null);
+ batch.setNumber(14);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 4. Test : ESP2 - Vrac/7
+ // \- ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
+ // -----------------------------------------------------------------------------
+ // batch : "ESP2 - Vrac/7 "
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setSpecies(taxon2);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(7f);
+
+ assertCreateAndReloadSpeciesBatch(batch, null);
+ esp2Batch = batch;
+
+ // Batch : ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11
+ batch = new SpeciesBatch();
+ batch.setId(null);
+ batch.setParentBatch(esp2Batch);
+ batch.setSpecies(taxon2);
+ batch.setComment("ESP2 - Vrac/7 UNK/2 ss-ech/1 Nombre/11");
+ batch.setSampleCategoryType(SampleCategoryEnum.maturity);
+ batch.setSampleCategoryValue(firstMaturityQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ batch.setWeight(1f);
+ batch.setNumber(11);
+
+ assertCreateAndReloadSpeciesBatch(batch, batch.getParentBatch().getId());
+
+ // -----------------------------------------------------------------------------
+ // 5. Test save after modifications
+ // -----------------------------------------------------------------------------
+ // Batch : ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99
+ batch.setComment("ESP2 - Vrac/7 UNK/1.75 ss-ech/1.11 Nombre/99");
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(unkQualitativeValue);
+ batch.setSampleCategoryWeight(1.75f);
+ batch.setWeight(1.11f);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setNumber(99);
+
+ // Save and reload, then check
+ SpeciesBatch savedBatch = service.saveSpeciesBatch(batch);
+ assertSpeciesBatch(savedBatch, batch, false);
+ SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), savedBatch.getId());
+ assertSpeciesBatch(savedBatch, reloadedBatch, true);
+
+ // Save batch for later
+ frequenciesParentBatch = batch;
+
+ // -----------------------------------------------------------------------------
+ // 6. Test change species
+ // -----------------------------------------------------------------------------
+ esp2Batch.setSpecies(taxon1);
+ service.changeSpeciesBatchSpecies(esp2Batch.getId(), taxon1);
+ assertSpeciesBatch(savedBatch, batch, false);
+ reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp2Batch.getId());
+ assertSpeciesBatch(esp2Batch, reloadedBatch, true);
+
+ // -----------------------------------------------------------------------------
+ // 7. Test get all root species
+ // -----------------------------------------------------------------------------
+ List<SpeciesBatch> rootSpeciesBatch = service.getAllRootSpeciesBatch(fishingOperationWithEmptyBatch.getId());
+ assertNotNull(rootSpeciesBatch);
+ assertEquals(2, rootSpeciesBatch.size());
+ assertNotNull(rootSpeciesBatch.get(0).getChildBatchs());
+ assertTrue(rootSpeciesBatch.get(0).getChildBatchs().size() > 0);
+ assertNotNull(rootSpeciesBatch.get(1).getChildBatchs());
+ assertTrue(rootSpeciesBatch.get(1).getChildBatchs().size() > 0);
+
+ // -----------------------------------------------------------------------------
+ // 8. Test batch frequency creation
+ // -----------------------------------------------------------------------------
+
+ List<SpeciesBatchFrequency> frequencies = Lists.newArrayList();
+ float lengthStep = 0.5f;
+ for (float length = lengthStep; length < lengthStep * 20; length += lengthStep) {
+ SpeciesBatchFrequency frequency = new SpeciesBatchFrequency();
+ frequency.setLengthStep(length);
+ frequency.setNumber((int) (length * 2));
+ frequency.setWeight(0.01f * length * 2);
+ frequency.setLengthStepCaracteristic(frequencyPMFM);
+ frequency.setBatch(frequenciesParentBatch);
+ frequency.setComment("comments");
+ frequencies.add(frequency);
+ }
+ List<SpeciesBatchFrequency> createdFrequencies = assertCreateAndReloadSpeciesBatchFrequency(frequencies, frequenciesParentBatch.getId());
+
+ // -----------------------------------------------------------------------------
+ // 9. Test batch frequency update
+ // -----------------------------------------------------------------------------
+ // Update some batchs (1cm, 2cm, etc)
+ for (SpeciesBatchFrequency speciesBatchFrequency : createdFrequencies) {
+ float length = speciesBatchFrequency.getLengthStep();
+ if ((float) (int) length == length) {
+ speciesBatchFrequency.setNumber(12);
+ speciesBatchFrequency.setComment(null);
+ }
+ }
+ // And remove the last item (should be deleted in DB)
+ createdFrequencies.remove(createdFrequencies.size()-1);
+ List<SpeciesBatchFrequency> savedFrequencies = service.saveSpeciesBatchFrequency(frequenciesParentBatch.getId(), frequencies);
+ assertBatchFrequencies(createdFrequencies, savedFrequencies, true);
+ }
+
+ @Test
+ public void deleteSpeciesBatch(/*String id*/) {
+ SpeciesBatch esp1Batch;
+ SpeciesBatch batch;
+ Species taxon1 = species.get(0);
+
+ // -----------------------------------------------------------------------------
+ // 1. Create two batchs (parent + child), then remove the parent batch
+ // -----------------------------------------------------------------------------
+ // batch : ESP1 Vrac/5
+ batch = new SpeciesBatch();
+ batch.setParentBatch(null);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted);
+ batch.setSampleCategoryValue(vracQualitativeValue);
+ batch.setSampleCategoryWeight(5f);
+ assertCreateAndReloadSpeciesBatch(batch, null);
+ esp1Batch = batch;
+
+ // batch : ESP1 Vrac/5 Male/2
+ batch = new SpeciesBatch();
+ batch.setParentBatch(esp1Batch);
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+ batch.setSpecies(taxon1);
+ batch.setSampleCategoryType(SampleCategoryEnum.sex);
+ batch.setSampleCategoryValue(maleQualitativeValue);
+ batch.setSampleCategoryWeight(2f);
+ assertCreateAndReloadSpeciesBatch(batch, esp1Batch.getId());
+
+ // Try to remove
+ service.deleteSpeciesBatch(esp1Batch.getId());
+
+ // Check if remove
+ try {
+ batch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), esp1Batch.getId());
+ assertNull(batch);
+ } catch (DataRetrievalFailureException drfe) {
+ assertNotNull(drfe);
+ }
+ }
+
+ protected void assertCreateAndReloadSpeciesBatch(SpeciesBatch batch, String parentBatchId) {
+ batch.setFishingOperation(fishingOperationWithEmptyBatch);
+
+ // Create batch
+ SpeciesBatch createdBatch = service.createSpeciesBatch(batch, parentBatchId);
+ assertSpeciesBatch(batch, createdBatch, false);
+
+ // then reload (for round trip check)
+ SpeciesBatch reloadedBatch = getSpeciesBatch(fishingOperationWithEmptyBatch.getId(), createdBatch.getId());
+ if (parentBatchId == null) {
+ assertNull(reloadedBatch.getParentBatch());
+ } else {
+ assertNotNull(reloadedBatch.getParentBatch());
+ assertEquals(parentBatchId, reloadedBatch.getParentBatch().getId());
+ }
+ assertSpeciesBatch(createdBatch, reloadedBatch, false);
+
+ batch.setId(createdBatch.getId());
+ }
+
+ protected void assertCreateAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
+ CatchBatch createdCatchBatch = service.createCatchBatch(catchBatch);
+ assertNotNull(createdCatchBatch);
+ assertNotNull(createdCatchBatch.getId());
+ assertCatchBatch(catchBatch, createdCatchBatch, false);
+
+ CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
+ assertCatchBatch(createdCatchBatch, reloadedCatchBatch, true);
+
+ catchBatch.setId(createdCatchBatch.getId());
+ }
+
+ protected void assertSaveAndReloadCatchBatch(CatchBatch catchBatch, String fishingOperationId) {
+ CatchBatch savedCatchBatch = service.saveCatchBatch(catchBatch);
+ assertNotNull(savedCatchBatch);
+ assertNotNull(savedCatchBatch.getId());
+ assertCatchBatch(catchBatch, savedCatchBatch, false);
+
+ CatchBatch reloadedCatchBatch = service.getCatchBatchFromFishingOperation(fishingOperationId);
+ assertCatchBatch(savedCatchBatch, reloadedCatchBatch, true);
+ }
+
+ protected void assertCatchBatch(CatchBatch expectedCatchBatch,CatchBatch actualCatchBatch, boolean assertIdEquals) {
+ if (expectedCatchBatch == null) {
+ assertNull(actualCatchBatch);
+ return;
+ }
+
+ assertNotNull(actualCatchBatch);
+ if (assertIdEquals) {
+ assertEquals(expectedCatchBatch.getId(), actualCatchBatch.getId());
+ }
+ assertEquals(expectedCatchBatch.getCatchTotalWeight(), actualCatchBatch.getCatchTotalWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalSortedCarousselWeight(), actualCatchBatch.getCatchTotalSortedCarousselWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalSortedTremisWeight(), actualCatchBatch.getCatchTotalSortedTremisWeight());
+ assertEquals(expectedCatchBatch.getCatchTotalUnsortedWeight(), actualCatchBatch.getCatchTotalUnsortedWeight());
+
+ assertEquals(expectedCatchBatch.getSpeciesTotalSampleSortedWeight(), actualCatchBatch.getSpeciesTotalSampleSortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalSortedWeight(), actualCatchBatch.getSpeciesTotalSortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalUnsortedWeight(), actualCatchBatch.getSpeciesTotalUnsortedWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalInertWeight(), actualCatchBatch.getSpeciesTotalInertWeight());
+ assertEquals(expectedCatchBatch.getSpeciesTotalLivingNotItemizedWeight(), actualCatchBatch.getSpeciesTotalLivingNotItemizedWeight());
+ }
+
+ protected void assertSpeciesBatch(SpeciesBatch expectedBatch, SpeciesBatch actualBatch, boolean assertIdEquals) {
+ assertNotNull(actualBatch);
+ assertNotNull(actualBatch.getId());
+ if (assertIdEquals && expectedBatch.getId() != null) {
+ assertEquals(expectedBatch.getId(), actualBatch.getId());
+ }
+ assertEquals(expectedBatch.getWeight(), actualBatch.getWeight());
+ assertEquals(expectedBatch.getSampleCategoryType(), actualBatch.getSampleCategoryType());
+ if (expectedBatch.getSampleCategoryValue() != null && expectedBatch.getSampleCategoryValue() instanceof CaracteristicQualitativeValue) {
+ assertNotNull("Bad sampleCategoryValue : expected <" + ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId() + "> but was <null>",
+ actualBatch.getSampleCategoryValue());
+ assertEquals(
+ ((CaracteristicQualitativeValue) expectedBatch.getSampleCategoryValue()).getId(),
+ ((CaracteristicQualitativeValue) actualBatch.getSampleCategoryValue()).getId());
+ } else {
+ assertEquals(expectedBatch.getSampleCategoryValue(), actualBatch.getSampleCategoryValue());
+ }
+ assertEquals(expectedBatch.getSampleCategoryWeight(), actualBatch.getSampleCategoryWeight());
+ assertEquals(expectedBatch.getNumber(), actualBatch.getNumber());
+ assertEquals(expectedBatch.getComment(), actualBatch.getComment());
+
+ // Check species only if Vrac/HorsVrac or if batch has been load throw getAllxxx method
+ // (Because getSpeciesBatch(id) could not always retrieve the species)
+ if (expectedBatch.getSpecies() != null && (
+ expectedBatch.getSampleCategoryType() == SampleCategoryEnum.sortedUnsorted
+ || actualBatch.getSpecies() != null)) {
+ assertNotNull(actualBatch.getSpecies());
+ assertEquals(expectedBatch.getSpecies().getId(), actualBatch.getSpecies().getId());
+ }
+ }
+ protected List<SpeciesBatchFrequency> assertCreateAndReloadSpeciesBatchFrequency(List<SpeciesBatchFrequency> frequencies, String parentBatchId) {
+
+ // Create batch
+ List<SpeciesBatchFrequency> createdFrequencies = service.saveSpeciesBatchFrequency(parentBatchId, frequencies);
+ assertBatchFrequencies(frequencies, createdFrequencies, false);
+
+ // then reload (for round trip check)
+ List<SpeciesBatchFrequency> reloadedFrequencies = service.getAllSpeciesBatchFrequency(parentBatchId);
+ assertBatchFrequencies(createdFrequencies, reloadedFrequencies, true);
+
+ return createdFrequencies;
+ }
+
+ protected void assertBatchFrequencies(List<SpeciesBatchFrequency> expectedFrequencies, List<SpeciesBatchFrequency> actualFrequencies, boolean assertIdEquals) {
+ assertNotNull(actualFrequencies);
+ assertEquals(expectedFrequencies.size(), actualFrequencies.size());
+
+ // Store actual batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> expectedLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : expectedFrequencies) {
+ expectedLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ }
+
+ // Store expected batches into a map, using the length as key
+ Map<Float, SpeciesBatchFrequency> actualLengthMap = Maps.newHashMap();
+ for (SpeciesBatchFrequency speciesBatchFrequency : actualFrequencies) {
+ assertFalse("Duplicate lengthStep found in batchFrequencies, for length=" + speciesBatchFrequency.getLengthStep(), actualLengthMap.containsKey(speciesBatchFrequency.getLengthStep()));
+ actualLengthMap.put(speciesBatchFrequency.getLengthStep(), speciesBatchFrequency);
+ assertNotNull(speciesBatchFrequency.getId());
+ }
+
+ for (Float lengthStep : expectedLengthMap.keySet()) {
+ SpeciesBatchFrequency expectedBatchFrequency = expectedLengthMap.get(lengthStep);
+ SpeciesBatchFrequency actualBatchFrequency = actualLengthMap.get(lengthStep);
+ if (assertIdEquals) {
+ assertEquals(expectedBatchFrequency.getId(), actualBatchFrequency.getId());
+ }
+ assertNotNull(expectedBatchFrequency.getLengthStepCaracteristic());
+ assertEquals(expectedBatchFrequency.getLengthStepCaracteristic().getId(), actualBatchFrequency.getLengthStepCaracteristic().getId());
+ assertEquals(expectedBatchFrequency.getNumber(), actualBatchFrequency.getNumber());
+ assertEquals(expectedBatchFrequency.getWeight(), actualBatchFrequency.getWeight());
+ assertEquals(expectedBatchFrequency.getComment(), actualBatchFrequency.getComment());
+ //assertNotNull(expectedBatchFrequency.getBatch());
+ //assertEquals(expectedBatchFrequency.getBatch().getId(), actualBatchFrequency.getBatch().getId());
+ }
+ }
+
+ protected SpeciesBatch getSpeciesBatch(String fishingOperationId, String speciesBatchId) {
+ return getSpeciesBatch(speciesBatchId, service.getAllRootSpeciesBatch(fishingOperationId));
+ }
+
+ protected SpeciesBatch getSpeciesBatch(String speciesBatchId, List<SpeciesBatch> speciesBatchs) {
+ if (speciesBatchs == null) {
+ return null;
+ }
+ for (SpeciesBatch speciesBatch : speciesBatchs) {
+ if (speciesBatchId.equals(speciesBatch.getId())) {
+ return speciesBatch;
+ }
+ if (speciesBatch.getChildBatchs() != null) {
+ speciesBatch = getSpeciesBatch(speciesBatchId, speciesBatch.getChildBatchs());
+ if (speciesBatch != null) {
+ return speciesBatch;
+ }
+ }
+ }
+ return null;
+ }
+}
1
0
r412 - trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro
by tchemit@users.forge.codelutin.com 14 Feb '13
by tchemit@users.forge.codelutin.com 14 Feb '13
14 Feb '13
Author: tchemit
Date: 2013-02-14 11:40:25 +0100 (Thu, 14 Feb 2013)
New Revision: 412
Url: http://forge.codelutin.com/projects/tutti/repository/revisions/412
Log:
improve synchro model
Modified:
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 08:42:09 UTC (rev 411)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeHelper.java 2013-02-14 10:40:25 UTC (rev 412)
@@ -28,7 +28,7 @@
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import fr.ifremer.tutti.persistence.entities.TuttiEntities;
-import org.apache.commons.lang.time.DateUtils;
+import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.dialect.Dialect;
@@ -121,6 +121,28 @@
if (result.isSuccess()) {
+ // prepare model (compute update date, count rows to update,...)
+
+ for (TuttiTable tuttiTable : TuttiTable.values()) {
+
+ String tableName = tuttiTable.name();
+
+ TuttiTableMetadata table = remoteMeta.getTable(tableName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Prepare table: " + tableName);
+ }
+ prepareTable(table,
+ localConnection,
+ remoteConnection,
+ result);
+ }
+
+ long totalRows = result.getTotalRows();
+ if (log.isInfoEnabled()) {
+ log.info("Total rows to update: " + totalRows);
+ }
+
// prepare target (desactivate constraints)
prepareSynch(localConnection);
@@ -140,6 +162,14 @@
remoteConnection,
result);
}
+ if (log.isInfoEnabled()) {
+ long totalInserts = result.getTotalInserts();
+ long totalUpdates = result.getTotalUpdates();
+ log.info("Total rows to treat: " + totalRows);
+ log.info("Total rows inserted: " + totalInserts);
+ log.info("Total rows updated: " + totalUpdates);
+ log.info("Total rows treated: " + (totalInserts + totalUpdates));
+ }
} finally {
releaseSynch(localConnection);
}
@@ -231,9 +261,9 @@
* if table does not use a updateDate columns or if there
* is no data in table.
*/
- public Date getLastUpdateDate(Connection connection,
- TuttiTableMetadata table) throws SQLException {
- Date result = null;
+ public Timestamp getLastUpdateDate(Connection connection,
+ TuttiTableMetadata table) throws SQLException {
+ Timestamp result = null;
if (table.isWithUpdateDateColumn()) {
@@ -356,6 +386,7 @@
int columnCount = table.getColumnsCount();
String tableName = table.getName();
+ String tablePrefix = getTablePrefix(table) + " - " + result.getNbRows(tableName);
int[] pkIndex = table.getPkIndexs();
@@ -370,7 +401,6 @@
int countR = 0;
int insertCount = 0;
int updateCount = 0;
- int nbRowsToTreat = result.getNbRows(tableName);
while (incomingData.next()) {
List<String> pk = getPk(incomingData, pkIndex);
@@ -410,7 +440,7 @@
if (log.isDebugEnabled()) {
String pkAsString = pk.toString();
- log.debug(String.format("[%s] Execute query %s (pk:%s)", tableName, sql, pkAsString));
+ log.debug(String.format("%s Execute query %s (pk:%s)", tablePrefix, sql, pkAsString));
}
statement.addBatch();
@@ -427,7 +457,7 @@
}
if (countR % 10000 == 0) {
if (log.isInfoEnabled()) {
- log.info(String.format("[%s-%s] Rows Done: %s (inserts: %s, updates: %s)", tableName, nbRowsToTreat, countR, insertCount, updateCount));
+ log.info(String.format("%s Done: %s (inserts: %s, updates: %s)", tablePrefix, countR, insertCount, updateCount));
}
}
}
@@ -436,7 +466,7 @@
result.addInserts(tableName, insertCount);
result.addUpdates(tableName, updateCount);
if (log.isInfoEnabled()) {
- log.info(String.format("[%s-%s] Rows Done: %s (inserts: %s, updates: %s)", tableName, nbRowsToTreat, countR, insertCount, updateCount));
+ log.info(String.format("%s done: %s (inserts: %s, updates: %s)", tablePrefix, countR, insertCount, updateCount));
}
if (insertCount > 0 && insertCount % 1000 != 0) {
@@ -447,35 +477,29 @@
}
if (log.isDebugEnabled()) {
- log.debug(String.format("[%s] INSERT count: %s", tableName, result.getNbInserts(tableName)));
- log.debug(String.format("[%s] UPDATE count: %s", tableName, result.getNbUpdates(tableName)));
+ log.debug(String.format("%s INSERT count: %s", tablePrefix, result.getNbInserts(tableName)));
+ log.debug(String.format("%s UPDATE count: %s", tablePrefix, result.getNbUpdates(tableName)));
}
}
+ protected String getTablePrefix(TuttiTableMetadata table) {
+ return "[" + table.getName() + "(" + ReferentialSynchronizeHelper.IS_ASSOCIATION_TABLE.apply(table) + ")]";
+
+ }
+
public void synchronizeTable(TuttiTableMetadata table,
Connection localConnection,
Connection remoteConnection,
ReferentialSynchronizeResult result) throws SQLException {
- // get last updateDate used by local db
- Date updateDate = getLastUpdateDate(localConnection, table);
-
- if (updateDate != null) {
-
- // just inscrements of 1 milisecond to not having same
- updateDate = new Timestamp(DateUtils.setMilliseconds(updateDate, 0).getTime());
- updateDate = new Timestamp(DateUtils.addSeconds(updateDate, 1).getTime());
- }
String tableName = table.getName();
- long countToUpdate =
- getCountDataToUpdate(remoteConnection, table, updateDate);
+ String tablePrefix = getTablePrefix(table);
- if (log.isInfoEnabled()) {
- log.info(String.format("[%s] count to update: %s", tableName, countToUpdate));
- }
+ // get last updateDate used by local db
+ Date updateDate = result.getUpdateDate(tableName);
- result.addRows(tableName, (int) countToUpdate);
+ long countToUpdate = result.getNbRows(tableName);
if (countToUpdate > 0) {
@@ -490,7 +514,6 @@
// there is some data to update
-
TuttiTable tuttiTable = TuttiTable.valueOf(tableName);
if (tuttiTable.isAssociation()) {
PreparedStatement deleteStatement =
@@ -498,7 +521,7 @@
"DELETE FROM " + tableName);
deleteStatement.execute();
if (log.isInfoEnabled()) {
- log.info("Delete from association: " + tableName);
+ log.info(tablePrefix + " Delete association table");
}
}
@@ -506,7 +529,7 @@
Set<List<String>> existingIds = getExistingPrimaryKeys(localConnection, table);
if (log.isInfoEnabled()) {
- log.info("[" + tableName + "] existingIds: " + existingIds.size());
+ log.info(tablePrefix + " existingIds: " + existingIds.size());
}
// update table content
@@ -525,6 +548,36 @@
}
+ public void prepareTable(TuttiTableMetadata table,
+ Connection localConnection,
+ Connection remoteConnection,
+ ReferentialSynchronizeResult result) throws SQLException {
+
+ String tablePrefix = getTablePrefix(table);
+
+ String tableName = table.getName();
+
+ // get last updateDate used by local db
+ Timestamp updateDate = getLastUpdateDate(localConnection, table);
+
+ if (updateDate != null) {
+
+ // just inscrements of 1 milisecond to not having same
+ updateDate = new Timestamp(DateUtils.setMilliseconds(updateDate, 0).getTime());
+ updateDate = new Timestamp(DateUtils.addSeconds(updateDate, 1).getTime());
+ }
+
+ long countToUpdate =
+ getCountDataToUpdate(remoteConnection, table, updateDate);
+
+ if (log.isInfoEnabled()) {
+ log.info(String.format("%s nb rows to update: %s", tablePrefix, countToUpdate));
+ }
+
+ result.setUpdateDate(tableName, updateDate);
+ result.addRows(tableName, (int) countToUpdate);
+ }
+
public static void prepareSynch(Connection connection) throws SQLException {
PreparedStatement statement = connection.prepareStatement("SET REFERENTIAL_INTEGRITY FALSE;");
statement.executeUpdate();
Modified: trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java
===================================================================
--- trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 08:42:09 UTC (rev 411)
+++ trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/persistence/service/synchro/ReferentialSynchronizeResult.java 2013-02-14 10:40:25 UTC (rev 412)
@@ -28,6 +28,7 @@
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+import java.sql.Timestamp;
import java.util.Map;
import java.util.Set;
@@ -63,6 +64,13 @@
protected final Map<String, Integer> updateHits = Maps.newTreeMap();
/**
+ * timestamp of last update date (per table).
+ *
+ * @since 1.0
+ */
+ protected final Map<String, Timestamp> updateDateHits = Maps.newTreeMap();
+
+ /**
* All table treated.
*
* @since 1.0
@@ -94,6 +102,30 @@
return ImmutableSet.copyOf(tableNames);
}
+ public long getTotalRows() {
+ long result = 0;
+ for (Integer nb : rowHits.values()) {
+ result += nb;
+ }
+ return result;
+ }
+
+ public long getTotalInserts() {
+ long result = 0;
+ for (Integer nb : insertHits.values()) {
+ result += nb;
+ }
+ return result;
+ }
+
+ public long getTotalUpdates() {
+ long result = 0;
+ for (Integer nb : updateHits.values()) {
+ result += nb;
+ }
+ return result;
+ }
+
public int getNbRows(String tableName) {
Integer result = rowHits.get(tableName);
if (result == null) {
@@ -136,6 +168,14 @@
}
}
+ public Timestamp getUpdateDate(String tableName) {
+ return updateDateHits.get(tableName);
+ }
+
+ public void setUpdateDate(String tableName, Timestamp t) {
+ updateDateHits.put(tableName, t);
+ }
+
public void addTableName(String tableName) {
tableNames.add(tableName);
}
1
0